Cloud Functions中的实时数据库onWrite触发器具有null val()数据

时间:2018-04-21 09:57:30

标签: javascript android firebase firebase-cloud-messaging google-cloud-functions

我正在尝试使用firebase中的云函数实现推送通知触发器,但每次我尝试val函数都返回null。它没有识别pushID,我使用push()方法从android实现了数据库。 这是我的数据库结构  enter image description here

这是我创建帖子时推送通知的代码。

  //import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/Posts/Posts/{pushId}').onWrite( event => {

    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    var valueObject = event.data.val();

    // if(valueObject.photoUrl != null) {
    //   valueObject.photoUrl= "Sent you a photo!";
    // }

  // Create a notification
    const payload = {
        notification: {
            title:valueObject.tittle,
            body: valueObject.details,
            sound: "default"
        },
    };

  //Create an options object that contains the time to live for the notification and the priority
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };


    return admin.messaging().sendToTopic("pushNotifications", payload, options);
});

这是云功能控制台中的错误

enter image description here

使用OnCreate后编辑: -

   exports.pushNotification = functions.database.ref('/Posts/Posts/{pushid}').onCreate((snap, context) => {

const original = snapshot.val();
    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    // var valueObject = event.data.val();
 var valueObject = snap.val();
    // if(valueObject.photoUrl != null) {
    //   valueObject.photoUrl= "Sent you a photo!";
    // }

  // Create a notification
    const payload = {
        notification: {
            title:valueObject.tittle,
            body: valueObject.details,
            sound: "default"
        },
    };

1 个答案:

答案 0 :(得分:1)

您似乎没有将代码调整到新的Functions 1.0 SDK。这些差异详见:https://firebase.google.com/docs/functions/beta-v1-diff

正如您在Realtime Database section中的文档中所看到的,onWrite触发器现在为您提供了一个具有beforeafter属性的Change对象,用于获取数据库位置的值在更新之前或之后。

另外考虑一下你是否真的想要一个onCreate触发器,它更容易处理,并且只在新创建匹配位置的数据时触发一次。