Необработанный отказ: заголовки не могут быть установлены после их отправки - PullRequest
0 голосов
/ 29 мая 2018

Я создаю чат-бота в Dialogflow.Я пытаюсь добавить данные в базу данных, когда выдается ошибка Unhandled Rejection.

Это мой index.js файл.

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
//require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
var firestore = admin.firestore();
//var db = firebase.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

var addRef = firestore.collection('Admission');
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));
  console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
  let params = request.body.queryResult.parameters;


  /* function welcome (agent) {
    agent.add(`Welcome to my agent!`);
  } */

  /* function fallback (agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  } */

  let responseJson ={};

  function yourFunctionHandler(agent) {
    var docRef = firestore.collection('users');
    name = request.body.queryResult.parameters['myname'];
    coll = request.body.queryResult.parameters['college_name'];
    name = name.charAt(0).toUpperCase() + name.slice(1);
    let balanceresponse = {};
    console.log(name);
    return docRef.add({
      myname: name,
      college: coll
    })
    .then((querySnapshot)=>{
      balanceresponse = {
        "fulfillmentText": 'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'

      }
      console.log('before response.send()');
      response.send(balanceresponse); 
     /*  console.log('before response.send()');
      response.send({
        fulfillmentText:  
             'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'
        //response.json(responseJson);
        }); */
        console.log('after response.send()');
      return 1;
    })
    .catch(error => {
      response.send({
        fulfillmentText:  
          'Something went wrong with the database'
        });
    });
  }

  function AdmissionHandler(agent) {
      console.log("inside Admission Handler");
      let balanceresponse = {};
      let Question = request.body.queryResult.parameters['question'];
      addRef.where("Question", "==", Question)
      .get().then((querySnapshot)=>{
      if (querySnapshot) {
          console.log("Document data:");
          const tips = querySnapshot.docs;
          const tipIndex = Math.floor(Math.random() * tips.length);
          const tip = tips[0];
          balanceresponse = {
            "fulfillmentText": ' Anything else you wanna know?'

         }
         console.log('before response.send()');
         response.send(balanceresponse); 
          /*  response.send({
            fulfillmentText:  
            //firestore.collection(addRef.Answer)+ 
            ' Anything else you wanna know?'
          });  */
          return 1;
      } else {
          // doc.data() will be undefined in this case
          console.log("No such document!");
      }
    return 1;
    })
    .catch(function(error) {
      console.log("Error getting document:", error);
     });


  } 


  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
 // intentMap.set('Default Welcome Intent', welcome);
 // intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('GetName', yourFunctionHandler);
  intentMap.set('AdmissionCustom', AdmissionHandler);
  agent.handleRequest(intentMap);
});

Я получаю эту ошибку:

You can see the error that occurs in MyFunctionHandler on passing response.send()

Я видел несколько подобных вопросов здесь, но ни на один из них не было ответа,Может кто-нибудь, пожалуйста, помогите?Я застрял в этом уже больше недели.

1 Ответ

0 голосов
/ 29 мая 2018

Проблема в том, что функция yourFunctionHandler(agent) выполняет действия асинхронно, но не возвращает обещание.Вместо этого он ничего не возвращает, поэтому обработка немедленно возвращается без отправки сообщения.

Поскольку похоже, что myDoc.add() возвращает Обещание, это легко сделать, сделав это return myDoc.add(...).then(...) и так далее.Это может выглядеть примерно так:

  function yourFunctionHandler(agent) {
    return docRef.add({
      myname: name,
      college: coll
    })
    .then(()=>{
      response.send({
        fulfillmentText:  
          'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'
      });
      return 1;
    })
    .catch(error => {
      //console.log('érror',e);
      response.send({
        fulfillmentText:  
          'Something went wrong with the database'
        });
    });
  }

Кроме того, вы смешиваете обработку ответа самостоятельно (вызывая response.send()) и использование Dialogflow agent.handleRequest(), который создаст для вас ответ.

Вы должны либо использовать методы Dialogflow для генерации ответа с чем-то вроде

agent.add("No such document found.");

, либо сами использовать значения в JSON, чтобы определить, какой обработчик вызывать с чем-то вроде

const intentName = request.body.queryResult.intent.name;
const handler = intentMap[intentName];
handler();

(Возможно, вам придется изменить это. Похоже, из вашего кода вы используете Dialogflow v1, который я отразил, и путь для имени намерения меняется для v2. Вы также должны проверить, что обработчик несуществует, может захотеть отправить параметры и т. д.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...