Created
December 6, 2014 03:46
-
-
Save gnauhnoj/2bf0adb4049c191db888 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
var secret = require('./secret.js'); | |
var rest = require('restler'); | |
var crypto = require('crypto'); | |
var querystring = require('querystring'); | |
var fatSecretRestUrl = 'http://platform.fatsecret.com/rest/server.api'; | |
var apiKey = process.env.FATKEY ||secret.fatKey; | |
var sharedSecret = process.env.FATSECRET ||secret.fatSecret; | |
var querySecret = sharedSecret + '&'; | |
var parseNumStr = function(out) { | |
// handle different types of values | |
out = out.replace(/[^0-9\.]+/g,' ').split(' ').filter(function(n){ return !!n; }); | |
return out; | |
}; | |
var fatSecret = function(query, next) { | |
console.log('infatsecret', query); | |
var date = new Date(); | |
// Note that the keys are in alphabetical order | |
var reqObj = { | |
format : 'json', | |
max_results : 1, | |
method: 'foods.search', | |
oauth_consumer_key: apiKey, | |
oauth_nonce: Math.random().toString(36).replace(/[^a-z]/, '').substr(2), | |
oauth_signature_method: 'HMAC-SHA1', | |
oauth_timestamp: Math.floor(date.getTime() / 1000), | |
oauth_version: '1.0', | |
search_expression: query // test query | |
}; | |
// construct a param=value& string and uriEncode | |
var paramsStr = querystring.stringify(reqObj, '&', '='); | |
var sigBaseStr = 'POST&' + encodeURIComponent(fatSecretRestUrl) + '&' + encodeURIComponent(paramsStr); | |
var hashedBaseStr = crypto.createHmac('sha1', querySecret).update(sigBaseStr).digest('base64'); | |
reqObj.oauth_signature = hashedBaseStr; | |
rest.post(fatSecretRestUrl, { | |
data: reqObj, | |
}).on('complete', function(data, response) { | |
// console.log(query, data); | |
// TODO: revisit handling errors | |
var out; | |
if (data.foods) { | |
out = data.foods.food.food_description; | |
out = parseNumStr(out); | |
} | |
next(out); | |
}); | |
}; | |
module.exports = exports = { | |
fatSecret : fatSecret, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment