`Meteor.call` - Invoking server method from server code? - meteor

From Meteor docs I know that:
Meteor.call can be used anywhere
In which cases would you use Meteor.call from the server over directly calling a method from another module/class/object?
=== server/file.js ===
let myPromise = Meteor.callAsync('aServerMethod', options);
vs
=== server/file.js ===
let myPromise = aModule.aMethod(options);

One key difference would be that inside a Meteor.method, this is bound to the method invocation object, which provides a bunch of stuff like this.userId or this.unblock, see docs for more. You don't get this in regular functions.
Another one is, that all methods are callable from the client, as I'm sure you know. So if you want to do server-only stuff, I would not use a Meteor.method but a regular function instead. If I want to expose the serverMethod also to the client, I'd use a Meteor.method.

Related

How can I use collection.find as a result of a meteor method?

I'm trying to follow the "Use the return value of a Meteor method in a template helper" pattern outlined here, except with collections.
Essentially, I've got something like this going:
(server side)
Meteor.methods({
queryTest: function(selector) {
console.log("In server meteor method...");
return MyCollection.find(selector);
}
});
(client side)
Meteor.call('queryTest', {}, function(error, results) {
console.log("in queryTest client callback...");
queryResult = [];
results.forEach(function(result) {
// massage it into something more useful for display
// and append it to queryResult...
});
Session.set("query-result", queryResult);
});
Template.query_test_template.helpers({
query_test_result: function() {
return Session.get("query-result");
}
});
The problem is, my callback (from Meteor.call) doesn't even get invoked.
If I replace the Method with just 'return "foo"' then the callback does get called. Also, if I add a ".fetch()" to the find, it also displays fine (but is no longer reactive, which breaks everything else).
What gives? Why is the callback not being invoked? I feel like I'm really close and just need the right incantation...
If it at all matters: I was doing all the queries on the client side just fine, but want to experiment with the likes of _ensureIndex and do full text searches, which from what I can tell, are basically only available through server-side method calls (and not in mini-mongo on the client).
EDIT
Ok, so I migrated things publish/subscribe, and overall they're working, but when I try to make it so a session value is the selector, it's not working right. Might be a matter of where I put the "subscribe".
So, I have a publish that takes a parameter "selector" (the intent is to pass in mongo selectors).
On the client, I have subscribe like:
Meteor.subscribe('my-collection-query', Session.get("my-collection-query-filter"));
But it has spotty behaviour. On one article, it recommended putting these on Templates.body.onCreate. That works, but doesn't result in something reactive (i.e. when I change that session value on the console, it doesn't change the displayed value).
So, if I follow the advice on another article, it puts the subscribe right in the relevant helper function of the template that calls on that collection. That works great, but if I have MULTIPLE templates calling into that collection, I have to add the subscribe to every single one of them for it to work.
Neither of these seems like the right thing. I think of "subscribing" as "laying down the pipes and just leaving them there to work", but that may be wrong.
I'll keep reading into the docs. Maybe somewhere, the scope of a subscription is properly explained.
You need to publish your data and subscribe to it in your client.
If you did not remove "autopublish" yet, all what you have will automatically be published. So when you query a collection on client (in a helper method for example), you would get results. This package is useful just for quick development and prototyping, but in a real application it should be removed. You should publish your data according to your app's needs and use cases. (Not all users have to see all data in all use cases)

Meteor: How to call a server method which is independent of client and call it at regular interval?

I have a method that needs to be run only in the server (independent of client) and i want to run that method at regular intervals. This method calls 2 api's and upsert data into into db. Can anybody please clarify below doubts ?
do i have to write my method inside Meteor.method ?
Meteor.Method({ myMethod: function() {.....} });
Do i have to use setInterval inside Meteor.method itself ?
Do i have to write the my code inside Meteor.startup ?
As my task is pretty simple i.e calling external api's(dependent api for eg : first api provides student username and second api student details), is it fine to use just setInterval or should i use any metoer pacakge ?
How do i implement upsert in meteor ? its a very simple usert where i need to see if username already exist in db. if not, insert otherwise update.
Yes write the method like that.
You can call the method inside the server like this:
Meteor.setInterval(function() {
Meteor.call('yourMethod', arg1, arg2
}, 5000)
This code should be then inside /server folder or wrapped into
`if (Meteor.isServer) {
}`
This should do it.
No
start with interval and see?
You can read about upsert here http://docs.meteor.com/#/full/upsert

Meteor wrapAsync syntax

How do I use the Meteor wrapAsync?
Below is what I am trying to do
if (tempTreatment.groupId === undefined) {
// create new group
Meteor.wrapAsync(Meteor.call('createTreatmentGroup', salon, tempTreatment.groupName, tempTreatment.groupName));
// get group id
var getGroup = Meteor.wrapAsync(Meteor.call('getTreatmentGroup', salon, tempTreatment.groupName));
console.log(getGroup);
tempTreatment.groupId = getGroup._id;
}
I want to run these two Meteor.callfunctions synchronosly but I get undefined on console.log(getGroup); which shuold just return an object.
Meteor.wrapAsync is a server-side API designed to wrap Node.js asynchronous functions requiring a callback as last argument, to make them appear synchronous through the use of Futures, a Fibers sub-library. (more on this here : https://www.discovermeteor.com/blog/wrapping-npm-packages/)
It is not intended to be used client-side to turn asynchronous Meteor.call into a synchronous call because on the browser, Remote Method Invokation calls are ALWAYS asynchronous.
Long story short, you simply cannot achieve what you're trying to do, you have to use callbacks and nest your second method call inside the success callback of your first method call.

When is the "null" publish ready?

Having the following code on the server:
Meteor.publish(null, function(){
// Return some cursors.
})
will according to the documentation have the following effect: the record set is automatically sent to all connected clients.
How can I on the client side determine if all the documents published by this function has been received? If I would use a subscription instead, it would provide me with a ready callback, letting me know when all the documents been received. What's the matching way here? Or are the documents already received at the client when my client side code starts to execute?
I'm afraid there's no way to have a ready callback for so called universal subscriptions you mentioned above. Just have a look at this part of Meteor's code, where the publish and subscription logic is defined on the server. For convenience I'm copy/pasting the code below:
ready: function () {
var self = this;
if (self._isDeactivated())
return;
if (!self._subscriptionId)
return; // unnecessary but ignored for universal sub
if (!self._ready) {
self._session.sendReady([self._subscriptionId]);
self._ready = true;
}
}
The _subscriptionId is only given to named subscriptions, which are those that you would manually define using Meteor.subscribe method. The subscriptions corresponding to null publish functions, doesn't have their own _subscriptionId, so as you can see from the code above, the server is not event trying to send the ready message to the client.

Update document in Meteor mini-mongo without updating server collections

In Meteor, I got a collection that the client subscribes to. In some cases, instead of publishing the documents that exists in the collection on the server, I want to send down some bogus data. Now that's fine using the this.added function in the publish.
My problem is that I want to treat the bogus doc as if it were a real document, specifically this gets troublesome when I want to update it. For the real docs I run a RealDocs.update but when doing that on the bogus doc it fails since there is no representation of it on the server (and I'd like to keep it that way).
A collection API that allowed me to pass something like local = true this would be fantastic but I have no idea how difficult that would be to implement and I'm not to fond of modifying the core code.
Right now I'm stuck at either creating a BogusDocs = new Meteor.Collection(null) but that makes populating the Collection more difficult since I have to either hard code fixtures in the client code or use a method to get the data from the server and I have to make sure I call BogusDocs.update instead of RealDocs.update as soon as I'm dealing with bogus data.
Maybe I could actually insert the data on the server and make sure it's removed later, but the data really has nothing to do with the server side collection so I'd rather avoid that.
Any thoughts on how to approach this problem?
After some further investigation (the evented mind site) it turns out that one can modify the local collection without making calls to the server. This is done by running the same methods as you usually would, but on MyCollection._collection instead of just on Collection. MyCollection.update() would thus become MyCollection._collection.update(). So, using a simple wrapper one can pass in the usual arguments to a update call to update the collection as usual (which will try to call the server which in turn will trigger your allow/deny rules) or we can add 'local' as the last argument to only perform the update in the client collection. Something like this should do it.
DocsUpdateWrapper = function() {
var lastIndex = arguments.length -1;
if (arguments[lastIndex] === 'local') {
Docs._collection.update(arguments.slice(0, lastIndex);
} else {
Docs.update(arguments)
}
}
(This could of course be extended to a DocsWrapper that allows for insertion and removals too.)(Didnt try this function yet but it should serve well as an example.)
The biggest benefit of this is imo that we can use the exact same calls to retrieve documents from the local collection, regardless of if they are local or living on the server too. By adding a simple boolean to the doc we can keep track of which documents are only local and which are not (An improved DocsWrapper could check for that bool so we could even omit passing the 'local' argument.) so we know how to update them.
There are some people working on local storage in the browser
https://github.com/awwx/meteor-browser-store
You might be able to adapt some of their ideas to provide "fake" documents.
I would use the transform feature on the collection to make an object that knows what to do with itself (on client). Give it the corruct update method (real/bogus), then call .update rather than a general one.
You can put the code from this.added into the transform process.
You can also set up a local minimongo collection. Insert on callback
#FoundAgents = new Meteor.Collection(null, Agent.transformData )
FoundAgents.remove({})
Meteor.call 'Get_agentsCloseToOffer', me, ping, (err, data) ->
if err
console.log JSON.stringify err,null,2
else
_.each data, (item) ->
FoundAgents.insert item
Maybe this interesting for you as well, I created two examples with native Meteor Local Collections at meteorpad. The first pad shows an example with plain reactive recordset: Sample_Publish_to_Local-Collection. The second will use the collection .observe method to listen to data: Collection.observe().

Resources