Reputation: 337
When I am sending notifications from firebase cloud functions when the child is added to firebase database it successfully sends a notification but when I delete the child from firebase database I get the notification as a null message below is the screenshot link what I get a notification when I delete the child from firebase database
//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new debate created
exports.pushNotifications = functions.database.ref('app_title').onWrite(( change,context) => {
console.log('Push notification event triggered');
const app_title = change.after.val();
const payload = {notification: {
title: 'New Notification',
body: `${app_title}`
}
};
return admin.messaging().sendToTopic("appGlobal",payload)
.then(function(response){
console.log('Notification sent successfully:',response);
})
.catch(function(error){
console.log('Notification sent failed:',error);
});
});
Upvotes: 1
Views: 756
Reputation: 2319
change.after.val()
is null because it is deleted, you should return change.before.val()
for deleting operaion (Ref answer)
Check change like that for detecting delete
//Comment created
if (change.after.exists() && !change.before.exists()) {
return //TODO
});
//Comment deleted
} else if (!change.after.exists() && change.before.exists()) {
return //TODO
});
//Comment updated
} else if (change.after.exists() && event.data.previous.exists()) {
return //TODO
}
Instead of onWrite, you need to implement onCreate, onDelete for better results
onWrite(), which triggers when data is created, updated, or deleted in the Realtime Database.
onCreate(), which triggers when new data is created in the Realtime Database.
onUpdate(), which triggers when data is updated in the Realtime Database.
onDelete(), which triggers when data is deleted from the Realtime Database. (ref)
Upvotes: 2