0

当我没有检查previous.exists()时,我的firebase云端函数会被多次调用。 我收到多个推送通知。多次调用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); 
}); 
}); 

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

这是火力结构: enter image description here

回答

5

好像除非你做的多次写入到该位置它不应该被称为多次。如果您只想在第一次写入路径时发送通知,请尝试使用.onCreate而不是.onWrite。那么你不需要检查以前的数据。请参阅文档here,其中概述了不同的数据库触发器。

+0

很棒的想法。我刚看了你的教程。我很荣幸能得到专家的回答。 –

+0

伤心我现在只是没有得到我的数据。 onCreate函数为receiptFcmToken提供null。错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组。 –

+0

我想我有一个想法,当我打电话onWrite我的功能在每个孩子节点上执行时,它被添加。 onCreate只是在创建一个空节点时,并且在添加子节点之前提供我想。但我怎么得到孩子的价值观。 Iam有点困惑。 –