Skip to content

Instantly share code, notes, and snippets.

Created March 21, 2017 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7e00420cf2623b33b80d88880be04f65 to your computer and use it in GitHub Desktop.
Save anonymous/7e00420cf2623b33b80d88880be04f65 to your computer and use it in GitHub Desktop.
Firebase cloud function
var functions = require('firebase-functions');
var mainRequest = require('request');
var urlStr = "https://3rdpartyapi.com/v2/food";
var reqObj = {
url: urlStr,
method: 'POST',
headers: {
'Authorization': 'Bearer xxxxxxx',
'Content-Type': 'application/json',
'x-app-id': 'xxxx',
'x-app-key': 'xxxxxxx'
}
};
// cloud function
exports.getInfo = functions.https.onRequest((request, response) => {
// check what we've been sent from api.ai
console.log("parameters:"+JSON.stringify(request.body.result.parameters));
var food = JSON.stringify(request.body.result.parameters.food);
// Let's kick off the function that requests the 3rd party api
getInfoFrom3rdParty(food,nutrient,"sum");
// I know this function call is 'pointless' but I have been hacking the code
// to try to figure out the reason for the delay. I'll return
// a promise etc. when it's working better (<15secs!).
// I previously had the function in it's own module to help
// with local development and will return to that.
var resString = "We're looking up "+food;
// send something back to api.ai for instant feedback (to check the call's worked)
var payload = {
"speech": resString,
"source": "jo",
"displayText": resString
};
response.writeHead(200, {"Content-Type": "application/json"});
response.end(JSON.stringify(payload));
})
// secondary function - called from Firebase cloud function
function getInfoFrom3rdParty(food) {
// log that this call has been made
console.log("getInfoFrom3rdParty() called");
reqObj.body = '{"query": "'+food+'"}';
mainRequest(reqObj, function (error, response, body) {
bodyjson = JSON.parse(response.body);
var foodArr = bodyjson.foods;
// return something sensible if we don't get anything back
if (!foodArr) {
var tmpObj = JSON.parse(reqObj.body);
console.log("I'm afraid I couldn't find information about %s.", tmpObj.query);
return;
} else {
console.log("API returned: " + foodArr);
}
if (error) {
// todo: remember to check for "over limit" errors from api
console.log('error:', error);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment