Last active
August 29, 2015 14:13
-
-
Save holyjak/f2418f9d425e1de6a13b to your computer and use it in GitHub Desktop.
Code for https://wondersofcode.wordpress.com/?p=120, part 1
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 deferred = Q.defer(); | |
//get stats for all users: | |
var userStats = []; | |
mongoFacade.find({}, function(err, users){ // Async fetch from DB | |
users.forEach(function(user){ | |
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); | |
return; | |
} | |
var responseData = JSON.parse(data); | |
var steps = responseData.lifetime.total.steps; | |
userStats.push({ | |
user: { | |
id: user.fitbitId, | |
name: user.name | |
}, | |
data: responseData | |
}); | |
//complete promise if this is the last element in array: | |
if (users.indexOf(user) === users.length-1) { | |
return deferred.resolve(userStats); | |
} | |
} | |
); | |
}); | |
}); | |
return deferred.promise; | |
}; | |
module.exports = { | |
getUsersWithFitbitStats: getUsersWithFitbitStats | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment