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有點困惑。 –