多次调用 Firebase 云函数

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

你好,当我没有检查 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 结构:
enter image description here

最佳答案

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

关于多次调用 Firebase 云函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45907488/

相关文章:

android - 在 Message.builder 中, builder() 显示未解析的引用?

google-cloud-messaging - 服务器 API key : migration doc vs migration video

xamarin - 使用Xamarin.Firebase.Messaging对FirebaseInstanceId.Instance.Token进行了描述,并在Xamarin.Android中返回null

node.js - 我在服务或部署 Firebase 托管功能时遇到问题

reactjs - 监控 Firebase Auth 对象属性更改?

android - 有没有办法在本地模拟 Firebase 数据库?

android - 组织.gradle.api.tasks.TaskExecutionException : Execution failed for task ':transformDexArchiveWithExternalLibsDexMergerForDebug'

firebase - 如何获取/设置 firebase 云函数 v1 环境变量

javascript - Firebase:检查 onWrite 事件的 'write or delete'

android - 如何在 Firebase 实时数据库 Android 中实现等价于 .contains(SomeText) ?