I am building an Express Node.js appication using this Facebook SDK, and here is my current route for root:
app.get('/', Facebook.loginRequired(), function (req, res) {
req.facebook.api('/me', function(err, user) {
res.render('index', {title: 'title', user: user});
});
});
I am making a call to the FB open graph URL http://graph.facebook.com/me, but I'd like to make multiple open graph calls to pass to my template. For example:
var APIcalls = ['/me', '/me/music', '/me/music.listens'];
req.facebook.api(APIcalls, function(err, res1, res2, res3){
res.render('index', {res1: res1, res2: res2, res3: res3});
});
What is the easiest way to make multiple API calls to Facebook and then pass the responses to my template accordingly? You can see my full app.js file here. Thanks!
This scenario seems perfect for async.map see here: https://github.com/caolan/async#map
the async.map method takes an array of items and performs the same async call for each item in your array in parallel. If no errors are encountered, it will call a callback with a new array of results.
so your example would look something like this:
var async = require('async'),
APIcalls = ['/me', '/me/music', '/me/music.listens'];
async.map(APIcalls,
function(item, callback){
req.facebook.api(item, function(err, user) {
if(err){
return callback(err);
};
callback(null, user);
});},
function(err, results){
if(err){
throw new Error(err);
}
res.render('index', results);
}
);
For this you should use batching so that you can get away with only a single request to the Graph API.
FB.api('/', 'POST', {
batch: [{
relative_url: '/me'
},{
relative_url: '/me/music'
},{
relative_url: '/me/music.listens'
}]
}, function(o) {
console.log(o);
});
Alternatively you can use multi-fql
FB.api('/fql', {
q1: 'select ....',
q2: 'select ...'
}, function(o) {
console.log(o);
});
Once that is done, you simply combine the data into a single model that you pass to the renderer.