Server initialized call of meteor method?


#1

I need to be able to call meteor methods from server side. Or I need to be able to set a user context under which a function should be run.

So for example I have a function that should be called with a user context. I read a forum here https://github.com/meteor/meteor/issues/6388 which explains how to set userId from server initiated call like follows:


        let invocation = new DDPCommon.MethodInvocation({
          isSimulation: false,
          userId: request.userId,
          setUserId: ()=>{},
          unblock: ()=>{},
          connection: {},
          randomSeed: Math.random(),
        });

        DDP._CurrentInvocation.withValue(invocation, () => {
          console .log(".... " + Meteor.userId());
          myFunction(myargs);
        })

And this works for synchronous functions but I have a function which in turn starts up a new process and then I need to handle the results in asynchronous callback. When the callback is fired it seems that all context are gone. See below:

const process = ChildProcess.spawn(this.getCommand().executable, this.getCommand().args);
let someObjectINeedLater = ....
process.on('exit', Meteor.bindEnvironment(function (code, signal) {
    // Build a reply message which looks like originating from Yoda
    let reply = {};
    reply.id = someObjectINeedLater.id;   // <----- THIS DOES NOT EXIST ANYMORE
    ....

}

I have tried to use Meteor.bindEnvironment but without succeess. Any idea?

When I call the method from client with Meteor.call(...) then everything works as expected so I guess there are some minor thing I am missing here.


#2

I found the error. It had nothing to do with this, it was just a typo which caused this issue.

So the above solution is working as intended to call meteor methods from server side.