0

I want to be able to nose whatsapi in meteor. I am using

  • latest stable meteor
  • node-whatsapi
  • arunoda´s meteorhacks:npm

and can get the past the basics:

On meteor server startup, I have:

whatsapi = Meteor.npmRequire('whatsapi');
wa = whatsapi.createAdapter({
    msisdn: '....',
    username: '....',
    password: '....',
    ccode: '....'
});

wa.connect(function connected(err) {
    if (err) {console.log(err); return;}
    console.log('Connected');
    wa.login(logged);
});

function logged(err) {
    if (err) {console.log(err); return;}
    console.log('Logged in');
    wa.sendIsOnline();
};

... which let me send and receive messages with a method call to

wa.sendMessage(recipient, content, function(err, id) {
    if (err) {console.log(err.message); return;}
    console.log('Server received message %s', id);
});

The code bellow also works, logging received messages on the console. This sits inside server Meteor.startup:

wa.on('receivedMessage', function(message) {
    console.log("From: " + message.from);
    console.log(message.body);
});

My problem is that when I try to add store message.from or message.body into a collection, meteor gives me "Meteor code must always run within a Fiber" error")

wa.on('receivedMessage', function(message) {
    console.log("From: " + message.from);
    console.log(message.body);
    Recipients.insert({msgfrom: message.from});
});

Help!

Oren Pinsky
  • 419
  • 3
  • 19

1 Answers1

2

Use Meteor.bindEnvironment to wrap any callback given out by your npm module. It will wrap the callback into a 'Fiber' so you can run Meteor code in it.

For example:

wa.on('receivedMessage', Meteor.bindEnvironment(function(message) {
    console.log("From: " + message.from);
    console.log(message.body);
    Recipients.insert({msgfrom: message.from});
}));

What it does essentially is place the code in the callback into a Fiber.

Tarang
  • 75,157
  • 39
  • 215
  • 276