Node.js云函数“如果不存在,则get()中的firestore set()如果不存在”无法正常工作?

时间:2018-09-27 14:26:54

标签: node.js firebase google-cloud-firestore google-cloud-functions dialogflow

这是我要实现的目标

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);
});

但是执行上面的代码会启动云功能并首先终止,并且我的聊天机器人没有任何响应,但是执行日志后就像

  • 开始执行功能
  • 函数执行耗时404毫秒,已完成 状态代码:200
  • “文档已经存在 someusername

1 个答案:

答案 0 :(得分:1)

DocumentReference.set返回一个诺言,而您不必等待它完成。因此,如果您从以下位置更改代码,它应该可以工作:

usersRef.set({
    userName : 'somename'
});
... rest of the code

usersRef.set({
    userName : 'somename'
}).then(result => {
    ... rest of the code
})