Node.js 为Dialogflow Webhooks编写更好的代码

Node.js 为Dialogflow Webhooks编写更好的代码,node.js,firebase,google-cloud-firestore,dialogflow-es,chatbot,Node.js,Firebase,Google Cloud Firestore,Dialogflow Es,Chatbot,我目前正在使用节点后端中的dialogflow调用一个实现webhook,在firestore db上执行crud操作。有没有更好更干净的方法来写这些 我的代码似乎写得很糟糕,但它能工作。我正在努力编写更干净、可读性更强的代码,所以我正在寻找一位能够给我一些关于如何使用Webhook编写更好的API调用的建议的人 //DATABASE API CALLS HERE!// case "FAV_COLOR": agent.handleRequest(agent => {

我目前正在使用节点后端中的dialogflow调用一个实现webhook,在firestore db上执行crud操作。有没有更好更干净的方法来写这些

我的代码似乎写得很糟糕,但它能工作。我正在努力编写更干净、可读性更强的代码,所以我正在寻找一位能够给我一些关于如何使用Webhook编写更好的API调用的建议的人

//DATABASE API CALLS HERE!// 

  case "FAV_COLOR":
    agent.handleRequest(agent => {
      return new Promise(() => {
        async function writeToDb() {
          // Get parameter from Dialogflow with the string to add to the database doc
          const databaseEntry = agent.parameters.color;
          // Get the database collection 'user' and document 'color' and store
          // the document  {entry: "<value of database entry>"} in the 'color' document
          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");
//在此处调用数据库API!//
案例“FAV_颜色”:
agent.handleRequest(agent=>{
返回新承诺(()=>{
异步函数writeToDb(){
//使用要添加到数据库文档的字符串从Dialogflow获取参数
const databaseEntry=agent.parameters.color;
//获取数据库集合“用户”和文档“颜色”并存储
//“颜色”文档中的文档{条目:}
const dialogflowAgentRef=db.collection(“用户”).doc(“颜色”);
试一试{
wait db.runTransaction(事务=>{
transaction.set(dialogflowAgentRef{
条目:数据库条目
});
返还承诺。决议(“填写完整”);
});
agent.add(
`已将“${databaseEntry}”写入Firestore数据库`
);
}捕获(e){
agent.add(
`未能将“${databaseEntry}”写入Firestore数据库`
);
}
}
writeToDb();
});
});
打破
违约:
控制台日志(“其已损坏”);
它当前位于switch语句中,因为我希望根据操作触发不同的实现。两个agent.add语句都不会触发

另外,如果有人能提供一些调试这些程序的技巧,我将非常感激。我刚刚部署了这些函数,添加了一个console.log(JSON.stringify());然后在firebase控制台功能部分检查错误。似乎效率极低

感谢您抽出时间回答:)


杰克

你的
index.js

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const  welcome  = require('./welcome')
const  fallback  = require('./fallback')

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });
    console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
    console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    intentMap.set('Default Fallback Intent', fallback);
    agent.handleRequest(intentMap);
});
const welcome = (agent) => {
    agent.add(`Welcome to my agent!`);
}
module.exports = welcome
const fallback = (agent) => {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}
module.exports  =  fallback
您可以拆分文件,如欢迎、回退

=>
welcome.js

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const  welcome  = require('./welcome')
const  fallback  = require('./fallback')

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });
    console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
    console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    intentMap.set('Default Fallback Intent', fallback);
    agent.handleRequest(intentMap);
});
const welcome = (agent) => {
    agent.add(`Welcome to my agent!`);
}
module.exports = welcome
const fallback = (agent) => {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}
module.exports  =  fallback
=>
fallback.js

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const  welcome  = require('./welcome')
const  fallback  = require('./fallback')

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });
    console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
    console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    intentMap.set('Default Fallback Intent', fallback);
    agent.handleRequest(intentMap);
});
const welcome = (agent) => {
    agent.add(`Welcome to my agent!`);
}
module.exports = welcome
const fallback = (agent) => {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}
module.exports  =  fallback

你可以用同样的方法来解决这个问题

我投票把这个问题作为离题题来结束,因为它要求同行评审来改进工作代码。它更适合于专门为此目的而创建的。这个网站是为那些涉及无法正常工作的代码的问题而设的。非常感谢Ken,我将把问题转移到那里。这很有趣,你的提示确实简化了事情!谢谢你的回复。我发现,我必须在intentMap中传入代理,如下所示:
intentMap.set(“favColor”,updateDB(agent))
,才能让它工作。我现在已经拆分了我的文件,比如index.js、app.js和一个包含单独的意图文件列表的文件夹。我现在的问题是db调用似乎只有10%的时间有效。这绝对是一个单独的问题,也许我会用另一个线程来解决。感谢您的时间:)
intentMap.set('NAME',updateDB)您可以像这样直接分配函数,