node.js - 为 Dialogflow Webhooks 编写更好的代码
问题描述
我目前在我的节点后端调用一个带有对话流的实现 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");
它目前位于 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);
});
您可以拆分文件,如欢迎、后备
=>welcome.js
const welcome = (agent) => {
agent.add(`Welcome to my agent!`);
}
module.exports = welcome
=>fallback.js
const fallback = (agent) => {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
module.exports = fallback
您可以对示例使用相同的方法
推荐阅读
- azure - 关于 Google Colab 和其他用于大数据项目的云服务
- java - @RestController 和 @GetMapping 在简单的 Hello World 列表中不返回 JSON 数组
- reactjs - 使用上下文隔离时删除 Electron 中的侦听器
- zapier - 从 zapier 执行 zoho page sense 自定义跟踪事件
- python - 股票报价请求中的 alpha-vantage 重复值
- python - SimPy 上的网络模拟
- apache-spark-sql - Spark SQL 根据条件创建布尔列
- python - 如何标准化嵌套的.json?
- azure-machine-learning-studio - 无法在 azure ml 工作区中创建图像
- c# - 在带有数据库的 ASP.NET Core 5.0 应用程序中使用 Serilog 实现日志记录