0

我有一个名为 Users 的 firestore 集合,并试图通过履行在集合中编写文档。我正在通过对话流代理获取用户的姓名和他的位置,并尝试将其插入到集合中。但是文档没有被插入。

1)从代理获取数据:

名称=代理.参数.名称;

位置=代理.参数.位置;

2)写入firestore集合用户

db.collection("Users").doc("101").set({ name: name, location:location});

该函数已执行,但文档未插入到 firestore 集合中。我错过了什么?

'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const admin = require('firebase-admin');

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


var name='';
var location='';

admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

 function getUserDetails(agent)
 {
     name= agent.parameters.name;
     location=agent.parameters.location;
     console.log("buyer name is " + name);
     db.collection("Users").doc("101").set({
    name: name,
    location:location});
    agent.add(`User has been inserted`);   
 }

 intentMap.set('Buy Car', getUserDetails);
 agent.handleRequest(intentMap);
})
4

2 回答 2

1
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => 
 {const agent = new WebhookClient({request,response});
  function saveName(agent){
    const nameParam = agent.parameters.name;
    const name = nameParam;
    agent.add(`thank you, ` + name + `!`);

  return db.collection('test').add({name: name}).then((snapshot) => {(console.log('success'));
    });
  }

  let intentMap = new Map();
  intentMap.set('Get_Name', saveName);
  agent.handleRequest(intentMap);
 });
于 2019-02-17T05:43:58.177 回答
0

目前尚不清楚出了什么问题,但至少部分是因为您没有检查写入集合/文档时可能出现的错误。

您的回复“已插入用户”在您实际确认用户文档已设置的情况下发送,这使情况更加复杂。甚至无法保证它在函数完成时已经发送,因为您没有将文档写入视为异步。

执行此操作的正常方法是返回返回的 Promise set(),因此handleRequest()在发送回复之前将等待处理程序完成。您还应该then()在 Promise 的一部分中设置回复并捕获catch()块中的任何错误。

像这样的函数更正确,并且可以记录错误是什么:

 function getUserDetails(agent)
 {
     name= agent.parameters.name;
     location=agent.parameters.location;
     console.log("buyer name is " + name);
     return db.collection("Users").doc("101").set({
       name: name,
       location: location
     })
     .then( () => {
       agent.add(`User has been inserted`);   
     })
     .catch( err => {
       console.log( err );
       agent.add('Something went wrong');
     });
 }
于 2018-12-04T16:54:58.810 回答