Firebase Cloud功能事件 - 有时无法获取更新事件的数据

时间:2018-04-28 05:58:40

标签: javascript firebase firebase-realtime-database google-cloud-functions

我已经编写了firebase云功能来触发更新记录。有时候我没有得到相同的更新记录。我在下面添加我的代码。请检查附加图像。

exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}/userResponse').onUpdate(event => {
    return admin.database().ref(`/Notification/${event.params.userId}/${event.params.notificationId}`).once('value').then(function (snapshot) {
        var notification = snapshot.val();

        if (!notification) {
            console.error("Notification not found on notification update");
            return;
        };

我也可以从父级获取Notification对象,但我想知道问题最佳方法和此代码的问题。

this is error log

this is database structure

这是我的第一篇帖子,如果需要更多信息,请告诉我。 感谢

1 个答案:

答案 0 :(得分:0)

您不必在函数内调用once,因为它已经在您正在侦听的位置返回数据,只需监听父节点。

所以你应该这样做:

exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}').onUpdate(event => {
        const notification = event.data.val(); 

        if (notification === null) {
            console.error("Notification not found on notification update");
            return null;
            //actually this would only be called in case of deletion of the Notification
        } else {
            //do something with the notification data: send Android notification, send mail, write in another node of the database, etc.
           //BUT return a Promise
           //notification const declared above is a JavaScript object containing what is under this node (i.e. a similar structure than your database structure as shown in the image within your post.)
        }
});

我建议你看一下Firebase团队的这三个视频:

https://www.youtube.com/watch?v=7IkUgCLr5oA&t=517s

https://www.youtube.com/watch?v=652XeeKNHSk&t=27s

https://www.youtube.com/watch?v=d9GrysWH1Lc

另请注意,如果您使用的是高于1.0.0的CF版本,则云功能已更新,代码的第一行应以不同方式编写。见https://firebase.google.com/docs/functions/beta-v1-diff