这是我要实现的目标
if user is exist in firestore
show the data
else
add it to firestore
以下是我的代码
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
var db = admin.firestore();
const settings = {timestampsInSnapshots: true};
db.settings(settings);
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function save(agent) {
const usersRef = db.collection('users').doc('someid');
usersRef.get().then(function(doc) {
if(doc.exists) {
let existingUser = doc.data();
console.log("Document is already exists " + existingUser.userName);
agent.add('Hello ');
} else {
console.log("Document creation is started");
usersRef.set({
userName : 'somename'
});
agent.add('Welcome ');
}
}).catch(function(error) {
console.error("Error writing document: ", error);
agent.add('Failed to login!');
});
}
let intentMap = new Map();
intentMap.set('dialogflow-intent-name',save);
agent.handleRequest(intentMap);
});
但是执行上面的代码会启动云功能并首先终止,并且我的聊天机器人没有任何响应,但是执行日志后就像
答案 0 :(得分:1)
DocumentReference.set返回一个诺言,而您不必等待它完成。因此,如果您从以下位置更改代码,它应该可以工作:
usersRef.set({
userName : 'somename'
});
... rest of the code
到
usersRef.set({
userName : 'somename'
}).then(result => {
... rest of the code
})