I'm trying to push notification to android app whenever new posts are added. But the notifications arrive whenever the data is "changed" i.e even when posts are deleted which i don't require. How can i put a condition so that FCM sends notification only if the posts are added. Here is my index.js file
const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos').onWrite(event => {
var topic = "deals_notification";
let projectStateChanged = false;
let projectCreated = true;
let projectData = event.data.val();
if (!event.data.previous.exists()) {
// Do things here if project didn't exists before
}
if (projectCreated && event.data.changed()) {
projectStateChanged = true;
}
let msg = "";
if (projectCreated) {
msg = "A project state was changed";
}
if (!event.data.exists()) {
return;
}
let payload = {
notification: {
title: 'Firebase Notification',
body: msg,
sound: 'default',
badge: '1'
}
};
admin.messaging().sendToTopic(topic, payload).then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
}).catch(function(error) {
console.log("Error sending message:", error);
});
});