【问题标题】:Firebase Cloud Functions called multiple times多次调用 Firebase 云函数
【发布时间】:2017-08-27 17:23:13
【问题描述】:

您好,当我没有检查 previous.exists() 时,我的 firebase 云函数会被多次调用。 我收到多个推送通知。

if (!event.data.exists()){
    return;
}
if (event.data.previous.exists()){
    return;
}

但是当我检查它时,我没有收到推送通知。 这是不工作的代码: 我应该改变什么?

exports.sendShoppingListInvitationNotification = functions.database.ref('/invites/{id}/').onWrite(event => {
//get the snapshot of the written data
const snapshot = event.data;  

if (!event.data.exists()){
    return;
}
if (event.data.previous.exists()){
    return;
}

    //get snapshot values
    console.log(snapshot.key);
const receiptToken = snapshot.child('receiptFcmToken').val();
const senderName = snapshot.child('senderNickname').val();
const inviteMessage = snapshot.child('inviteMessage').val();
const senderImage = snapshot.child('senderProfileImageURL').val();


//create Notification
const payload = {
    notification: {
        title: `Invitation from ${senderName}`,
        body:  `${inviteMessage}`,
        icon: `${senderImage}`,
        badge: '1',
        sound: 'default',
    }
};               

//send a notification to firends token   
return admin.messaging().sendToDevice(receiptToken, payload).then(response => { 
     console.log("Successfully sent message:", response);
 }).catch((err) => {
    console.log(err);
});   
});

我在云控制台上没有收到错误消息。

这是 firebase 结构:

【问题讨论】:

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


    【解决方案1】:

    似乎不应该多次调用它,除非您对该位置进行多次写入。如果您只想在第一次写入路径时发送通知,请尝试使用 .onCreate 而不是 .onWrite。然后你就不需要检查以前的数据了。请参阅文档here,其中概述了不同的数据库触发器。

    【讨论】:

    • 好主意。我刚看了你的教程。很荣幸得到专家的解答。
    • 很遗憾我现在没有得到我的数据。 onCreate 函数为receiptFcmToken 传递null。错误:提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组。
    • 我想我在调用 onWrite 时有了一个想法,我的函数在添加时在每个子节点上执行。 onCreate 仅在创建时和我认为添加子节点之前提供一个空节点。但是我如何获得孩子的价值观。我有点困惑。
    • 如何将数据添加到数据库中?我测试了您的代码,它按预期工作。但是,如果您一次或成组地添加每个 id 的一些子代,而不是作为一个子代,则每次添加时都会调用该函数。将数据添加到数据库的代码是什么?
    • 似乎假设 Cloud Firestore 触发的函数只会执行一次是不安全的:请参阅此处 stackoverflow.com/questions/48735862/… 和此处:stackoverflow.com/questions/49217120/… 我遇到了聚合问题。真的认为应该更改文档以突出显示这一点:firebase.google.com/docs/firestore/solutions/… 如果不是幂等的,可能很少发生并且是痛苦的错误。
    猜你喜欢
    • 2018-10-02
    • 2019-06-29
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2021-09-13
    • 2018-05-17
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多