I'm currently calling a fulfillment webhook with dialogflow
in my node backend, performing crud operations on a firestore db. Is there a better, cleaner way to write these?
My code seems very poorly written but it works. I am striving to write cleaner more readable code so I'm looking for someone to give me some pointers on how to write better API calls with webhooks.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
//DATABASE API CALLS HERE!//
switch (agent.action) {
case "FAV_COLOR":
agent.handleRequest(agent => {
return new Promise(() => {
async function writeToDb() {
const databaseEntry = agent.parameters.color;
const dialogflowAgentRef = db.collection("user").doc("color");
try {
await db.runTransaction(transaction => {
transaction.set(dialogflowAgentRef, {
entry: databaseEntry
});
return Promise.resolve("Write complete");
});
agent.add(
`Wrote "${databaseEntry}" to the Firestore database.`
);
} catch (e) {
agent.add(
`Failed to write "${databaseEntry}" to the Firestore database.`
);
}
}
writeToDb();
});
});
break;
default:
console.log("ITS BROKEN");
});
It's currently inside a switch statement because I want to trigger different fulfillments based on actions. Neither agent.add
statement is triggered.
Also, if someone could throw in some tips about debugging these I would really appreciate it. I've just been deploying the functions, adding a console.log(JSON.stringify());
and then checking in the firebase console functions section for errors. Seems incredibly inefficient.