Firebase云功能多次调用

Pet*_*pek 4 firebase google-cloud-functions firebase-cloud-messaging

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

if (!event.data.exists()){
    return;
}
if (event.data.previous.exists()){
    return;
}
Run Code Online (Sandbox Code Playgroud)

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

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);
});   
});
Run Code Online (Sandbox Code Playgroud)

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

这是firebase结构: 在此输入图像描述

Jen*_*son 8

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

  • 似乎假设云 Firestore 触发的函数只会执行一次是不安全的:请参阅此处 /sf/ask/3411510371/ 和此处:https ://stackoverflow.com/questions/49217120/how-to-make-idempotent-aggregation-in-cloud-functions/50860068#50860068 我在聚合时遇到了这个问题。真的认为应该更改文档以突出显示这一点:https://firebase.google.com/docs/firestore/solutions/aggregation#solution_cloud_functions 如果不是幂等的,可能很少发生并且是痛苦的错误。 (2认同)

归档时间:

查看次数:

2521 次

最近记录:

8 年,4 月 前