Meteor methods and remote API calls

11-09-2014 (d-m-Y)

Meteor methods is nice concept but when we want to use remote API calls, there can be unexpected results.

For example, you want to show users from remote API. On the client you will do:

//client
Template.hello.helpers({
  remoteUsers: function() {
    Meteor.call('getRemoteUsers', function(err, users) {
      Session.set('remoteUsers', users);
    });
    return Session.get('remoteUsers');
  }
})

Method getRemoteUsers can look like this:

//server
Meteor.methods({
  getRemoteUsers: function() {
    Future = Npm.require('fibers/future');
    var future = new Future();

    //simulate longer response. This can be call to remote API
    setTimeout(function() {
      future.return([ 'Peter', 'John', 'Monica', 'Julia' ]);
    }, 2000);

    //wait for future.return
    return future.wait();
  }
});

So the first time remoteUsers helper is called, getRemoteUsers method is called and Session.get('remoteUsers') returns undefined. When getRemoteUsers method returns result, Session is changed and remoteUsers helper is called again. So getRemoteUsers method is also called again. And when it returns users, Session is changed with the same data as before. This causes unnecessary double API call.

We can do something like this:

Template.hello.helpers({
  remoteUsers: function() {
    //call getRemoteUsers only when remoteUsers session is falsey
    if (!Session.get('remoteUsers')) {
      Meteor.call('getRemoteUsers', function(err, users) {
        Session.set('remoteUsers', users);
      });
    }
    return Session.get('remoteUsers');
  }
});

But this is not elegant solution. Elegant solution would be not using Session at all. When Meteor.call could return result from method synchronously.

Here you can see more code: https://github.com/Elfoslav/meteor-methods

← All articles | If you want to know about new blogposts you should follow @elfoslav

comments powered by Disqus