AWS lambda到firebase实时数据库未更新

时间:2017-09-04 16:15:52

标签: node.js firebase lambda firebase-realtime-database

 'use strict';

var Firebase = require('firebase');

var config = {
  apiKey: "apiKey",
  authDomain: "projectId.firebaseapp.com",
  databaseURL: "https://databaseName.firebaseio.com",
  storageBucket: "bucket.appspot.com"
};

  if(Firebase.apps.length === 0) {
      Firebase.initializeApp(config);
  }

exports.handler = function(event, context,callback) {

    try{
      var request = event.request;

      if(request.type === "LaunchRequest"){
        let options = {};
        options.speechText= "Welcome to TV. Using this skill you can control over 60 channels on your tv. To change to a different channel? You can say for example, play BBC Earth on tv";
        options.endSession= false;
        context.succeed(buildResponse(options));

      }else if(request.type ==="IntentRequest"){
        let options ={};
            if(request.intent.name === "ChannelIntent"){

               var message = 'hey guys';
               var ref = Firebase.database().ref().child("hello");
                var messagesRef = ref.child('messages');
                var messageRef = messagesRef.push(message);

                let ChannelName = request.intent.slots.ChannelName.value;
                options.speechText= "Channel changed to " +ChannelName+ ". ";
                options.endSession= true;
                context.succeed(buildResponse(options));
            }else{
                throw "unknown intent type";
            }

      }else if(request.type ==="SessionEndedRequest"){

      }else{
            throw "unknown intent type";
      }

    } catch(e){
      context.fail("Exception: "+e);
    }
}


function buildResponse(options){
  var response = {
    version: "1.0",
    response:{
      outputSpeech: {
        type: "PlainText",
        text: options.speechText
      },
      shouldEndSession: options.endSession
    }
  };

  if(options.repromptText){
    response.reponse.reprompt ={
      outputSpeech: {
        type: "PlainText",
        text: options.repromptText
      }
    };
  }
  return response;
}

这个想法是使用alexa技能来控制Android电视应用程序。 firebase用于将alexa技能连接到android tv应用程序。代码在AWS lambda中成功运行,但firebase db未更新。 如果有人遇到类似问题并找到解决方案,请分享解决方案。

我将添加我的aws lambda函数的代码片段。

1 个答案:

答案 0 :(得分:0)

大多数Firebase操作都是异步的,因此您不能仅仅假设成功。您必须等待电话完成:

messagesRef.push(message, (err) => {
  if (err) return context.fail(err);
  let ChannelName = request.intent.slots.ChannelName.value;
  options.speechText= "Channel changed to " +ChannelName+ ". ";
  options.endSession= true;
  context.succeed(buildResponse(options));
})