silvrgit/lib/today/fitbit.js

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-04-18 09:17:56 +00:00
const jsonfile = require('jsonfile');
const config = require('../../config/config.json');
const Fitbit = require('fitbit-oauth2');
2017-04-18 09:17:56 +00:00
const logger = require('log4js').getLogger();
require('sugar-date');
2017-04-18 09:17:56 +00:00
const fitbit = new Fitbit(config.fitbit);
const tokenFile = 'fb-token.json';
module.exports = {
getYesterdayFitbit: function() {
return new Promise(function(resolve, reject) {
2017-04-18 09:17:56 +00:00
const yesterday = Date.create('yesterday').format('{yyyy}-{MM}-{dd}');
const 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);
}
2017-04-18 09:17:56 +00:00
const 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) {
2016-04-11 14:12:44 +00:00
logger.error('Today Fitbit token failed to load');
logger.warn(err);
}
else {
logger.info('Fitbit token loaded...');
fitbit.setToken(obj);
}
});