2
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review. Please show your an excerpt of your code that has enough context so that we can understand what is going on and give you the proper advice. \$\endgroup\$ – 200_success Sep 13 at 17:22
  • 1
    \$\begingroup\$ Hi, I've added the full context of the code. What it is doing is pushing a JSON response from dialogflow via webhook to the firebase firestore and updating a users favorite color. \$\endgroup\$ – devjacks Sep 13 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.