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 => {
return admin.messaging().sendToDevice(tokens, payload).then(response => {
const toRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
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);
});
});
});
})
source
share