Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Functions called multiple times

Hello my firebase cloud function gets called multiple times when I don't put in check for previous.exists(). I get multiple push notifications.

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

But when I check for it i don't get push notification. Here is the not working code: What should I change?

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);
});   
});

I don't get error message on cloud console.

This is the firebase structure: enter image description here

like image 976
Peter Sypek Avatar asked Jan 29 '23 17:01

Peter Sypek


1 Answers

Seems like it shouldn’t be called multiple times unless you’re doing multiple writes to that location. Try using .onCreate instead of .onWriteif you only want to send a notification on the first write to the path. Then you won’t need that check for previous data. See the documentation here which outlines the different database triggers.

like image 144
Jen Person Avatar answered Feb 11 '23 07:02

Jen Person