Access to this.userId does not work when called from Meteor.SetTimeout

I'm trying to access the this.userId variable from a call to Meteor.methods, but it doesn't seem to work when I try to call a method through Meteor.setTimeout or Meteor.setInterval.

This is what I have:

 if (Meteor.is_server) { Meteor.methods({ getAccessToken : function() { try { console.log(this.userId); return Meteor.users.findOne({_id: this.userId}).services.facebook.accessToken; } catch(e) { return null; } } }); var fetch_feed = function() { console.log(Meteor.call("getAccessToken")); [...] // A bunch of other code }; Meteor.startup(function() { Meteor.setInterval(fetch_feed, 60000); // fetch a facebook group feed every minute Meteor.setTimeout(fetch_feed, 3000); // initially fetch the feed after 3 seconds }); } 

Watching the terminal log, this.userId always returns zero. But if I try to call the method from the client side or through the console, it will return the correct identifier.

Why does this not work from Meteor.setInterval? Is this a mistake or am I doing something wrong?

+4
source share
2 answers

Meteor userId associated with client connections. The server can interact with many clients, and this.userId inside the method will tell you which client asked to run this method.

If the server uses Meteor.call () to run the method, then it will not have userId since it is not running for any client.

These methods allow clients to call functions that will be executed on the server. For things that the server will run on its own, the javascript function will work.

+2
source

There is a solution that I used - sometimes you don’t want the method to be a function, but you really want it to remain a method. In this case, hack this work:

  var uniqueVar_D8kMWHtMMZJRCraiJ = Meteor.userId(); Meteor.setTimeout(function() { // hack to make Meteor.userId() work on next async // call to current method if(! Meteor._userId) Meteor._userId = Meteor.userId; Meteor.userId = function() { return Meteor._userId() || uniqueVar_D8kMWHtMMZJRCraiJ }; Meteor.apply(methodName, args); } , 100); 

Some brief explanation: we save Meteor.userId in Meteor._userId and overwrite Meteor.userId with a function that returns Meteor._userId() if it is true, and the rest is the historical value of Meteor.userId() before this happens. This historical meaning is preserved in the impossible to meet twice in the var name so that contextual conflicts cannot occur.

-1
source

All Articles