I am creating a chat bot in DialogFlow CX that is calling a node.js function in Google Cloud Functions that makes an external API Call. As an aside I am new to all three of these but feel like I am pretty close. The problem I am running into is my google cloud function is finishing and sending a response back to DialogFlow Cx prior to my external api call finishing up. I know my external API call is working and finishing because in logs I see that after the main google cloud function completes that the results of the API call are logged, I just need it to finish before the main google cloud function can finish. Any help is appreciated. Below is the code and log messages.
Code
const functions = require('@google-cloud/functions-framework');
const https = require('https');
let orderStatus = "Unknown";
//helloHttp is entry point for google cloud
exports.helloHttp =(req, res) => {
const orderNumber = req.body.sessionInfo.parameters.ordernumber;
console.log(orderNumber);
orderStatus = getOrderStatus(orderNumber, orderStatus);
const jsonResponse = {
fulfillment_response: {
messages: [
{
text: {
text: [orderStatus],
},
},
],
},
};
res.status(200).send(jsonResponse);
console.log(orderStatus)
};
function getOrderStatus(orderNumber, orderStatus){
var options = {
'secret stuff'
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
let rawData = ''
res.on('data', chunk => {
rawData += chunk
})
res.on('end', () => {
const parsedData = JSON.parse(rawData)
console.log(parsedData);
orderStatus = parsedData.order.status;
console.log(orderStatus);
})
});
req.on('error', (e) => {
console.error(e);
});
req.end();
return orderStatus
};
Logs
2023-09-18 17:44:12.522 EDT
getOrder382rngukw4pe Function execution started
2023-09-18 17:44:12.551 EDT
getOrder382rngukw4pe 46824
2023-09-18 17:44:12.739 EDT
getOrder382rngukw4pe Unknown
2023-09-18 17:44:12.740 EDT
getOrder382rngukw4pe Function execution took 217 ms, finished with status code: 200
2023-09-18 17:44:12.792 EDT
getOrder382rngukw4pe statusCode: 200
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe {
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe order: {
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe delivery: null,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe external_reference_number: null,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe id: ‘46824’,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe pickup: null,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe return: null,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe shipping: null,
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe status: ‘cancelled’
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe }
2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe }
2023-09-18 17:44:12.795 EDT
Thought maybe this is an async problem but not really sure how to address