Last active
August 29, 2015 14:13
-
-
Save holyjak/59ae7cb95c02769941e8 to your computer and use it in GitHub Desktop.
Code for https://wondersofcode.wordpress.com/?p=120, part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Q = require('q'); | |
var mongoFacade = require('mongoFacade'); | |
/** For each user in our DB, fetch her stats from Fitbit */ | |
var getUsersWithFitbitStats = function(){ | |
var deferredResults = Q.defer(); | |
mongoFacade.find({}, function(err, users){ // Async fetch from DB | |
// Turn each user into a promise of user stats | |
var userStatsPromisses = users.map(function(user){ | |
var userStatsPromise = Q.defer(); | |
Auth.oauth.getProtectedResource( | |
'https://api.fitbit.com/1/user/-/activities.json', | |
'GET', | |
user.oauthAccessToken, | |
user.oauthAccessTokenSecret, | |
function (error, data, response) { // Async fetch stats from Fitbit | |
if (error) { | |
logError(error, user); | |
userStatsPromise.reject(error); // don't hide the failure from the caller | |
return; | |
} | |
var responseData = JSON.parse(data); | |
// Deliver the promissed data | |
userStatsPromise.resolve({ | |
user: { | |
id: user.fitbitId, | |
name: user.name | |
}, | |
data: responseData | |
}); | |
} | |
); | |
return userStatsPromise.promise; // return an element of the new array | |
}); // users.map | |
// Wait for all of the userStats promisses to finish, filter out failures, | |
// return the rest as an array of user stats | |
//userStatsPromisses; -> deferredResults | |
Q.allSettled(userStatsPromisses).then(function (results) { | |
var fulfilled = function(r) { | |
return r.state === "fulfilled"; | |
}; | |
var getValue = function(r) { | |
return r.value; | |
}; | |
var goodUserStats = results.filter(fulfilled).map(getValue); | |
deferredResults.resolve(goodUserStats); | |
}); | |
}); // async mongoFacade.find | |
return deferredResults.promise; | |
}; | |
module.exports = { | |
getUsersWithFitbitStats: getUsersWithFitbitStats | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment