var jsonfile = require('jsonfile'); var config = require('../../config/config.json'); var Fitbit = require('fitbit-oauth2'); var dateFormat = require('dateformat'); var logger = require('log4js').getLogger(); require('sugar-date'); var fitbit = new Fitbit(config.fitbit); var tokenFile = '../fb-token.json'; module.exports = { getYesterdayFitbit: function() { return new Promise(function(resolve, reject) { var yesterday = Date.create('yesterday').format('{yyyy}-{MM}-{dd}'); var url = 'https://api.fitbit.com/1/user/-/activities/date/' + yesterday +'.json'; logger.info('Getting fitbit for: ', yesterday); logger.debug(url); fitbit.request({ uri: url, method: 'GET' }, function( err, body, token ) { if ( err ) { return reject(err); } var profile = JSON.parse( body ); // if token is not null, a refesh has happened and we need to persist the new token if ( token ) jsonfile.writeFile(tokenFile, token, function( err ) { if ( err ) { return reject(err); } return resolve(profile); }); else { return resolve(profile); } }); }); } }; jsonfile.readFile(tokenFile, function(err, obj) { if (err) { logger.error('Today Fitbit token failed to load'); logger.warn(err); } else { logger.info('Fitbit token loaded...'); fitbit.setToken(obj); } });