Cloud functions for Firebase onWrite database run twice

Hi, I am developing a notification system, but I am unable to delete the processed notification data. The event listener onWritefires twice, resulting in two notifications.

Can you help me find a job so that the onWrite event listener does not start twice? It is important to delete the processed data.

exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */

return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });

      //Deletes processed notification
      console.log("Removing notification");
      const getNotificationPromise = admin.database().ref(`/notification/message/${recipientUid}/${senderUid}`).once('value');
      return Promise.all([getNotificationPromise]).then(results => {
        const notificationSnapshot = results[0];
        toRemove.push(notificationSnapshot.ref.remove());

        console.log("Removing tokens.")
        return Promise.all(toRemove);
      });
      //return Promise.all(tokensToRemove);
    });
});

})
+4
source share
2 answers

. ( ), . , . .

, . , . '/notification/message/{recipientUid}/{senderUid}' - ​​ , . . , , , , , .

, Promise.all(), . then() then().

, , .

+6

- , firebase-functions v0.5.9; onCreate(), onUpdate() onDelete(). , ​​ firebase, ,

npm install --save firebase-functions 

, firebase sample, onWrite(), , node, .. write; . , . - :

   //if data is not new 
    if (event.data.previous.exists()) {return}
    // Exit when the data is deleted; needed cuz after deleting the node this function runs once more.
    if (!event.data.exists()) {return}

.

+1

Source: https://habr.com/ru/post/1673662/


All Articles