【发布时间】:2020-03-07 21:59:08
【问题描述】:
我已使用 Firestore 从 Dialogflow 上的输入数据写入数组,例如 this。
但我不知道如何从 Firestore 中获取数据以显示在 Dialogflow 中,下面是我的程序。
这就是我想要实现的目标。当我在 Dialogflow 中输入数字时,我想从 Firestore 实例中获取一个数字数组。
const db = admin.firestore();
db.settings({timestampsInSnapshots: true});
.
.
.
const sessionId = request.body.session.split("/").reverse()[0]; // or agent.session
function read(agent){
const number = agent.parameters.number; // when I input the number in Fialogflow
const docRef = db.collection('orders').doc(sessionId);
return docRef.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
console.log(doc);
} else {
agent.add(doc.data().orders);
}
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
});
}
function writeOrderToDb (newOrder) {
const docRef = db.collection('orders').doc(sessionId);
return db.runTransaction(t => {
return t.get(docRef)
.then(doc => {
t.update(docRef, {
orders: admin.firestore.FieldValue.arrayUnion(newOrder)
}, {merge: true});
/*if (!doc.data()) {
t.set(docRef, { orders: [newOrder] });
}
else {
t.update(docRef, {
orders: admin.firestore.FieldValue.arrayUnion(newOrder)
});
}*/
});
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
});
}
function confirmOrder(agent) {
const order = agent.context.get('order'),
amount = order.parameters.amount,
size = order.parameters.size,
type = order.parameters.type;
agent.add(`Confirming ${amount} ${type} in ${size}`);
// important to return, otherwise console.logs will not appear and non-deterministic behavior will ocurr
return writeOrderToDb({
"type": type,
"size": size,
"amount": amount
});
}
【问题讨论】:
-
我认为在这里 [1] 您将能够找到一个关于将对话流与 Firestore 连接的好示例。 [1]stackoverflow.com/questions/51692357/…
-
我知道你的意思。尽管我们使用 Firestore 在 Dialogflow 上获取数据,但我想获取每个数组的“sessionId”。比如我在Dialogflow上输入第一个,然后我会得到第一个数组的值。
标签: node.js google-cloud-firestore dialogflow-es-fulfillment