Determining whether data is added or deleted to Fi

2019-06-05 22:49发布

问题:

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

回答1:

You're doing two things wrong:

  • Your function is now triggered whenever any data is written under /promos. You want it to be triggered whenever a specific promo is written: /promo/{promoid}.

  • You're complete ignoring whether the data already existed: if (!event.data.previous.exists()) {, so will need to wire that up.

So something closer to this:

const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos/{promoId}').onWrite(event => {
    if (!event.data.previous.exists()) {
        let topic = "deals_notification";
        let payload = {
            notification: {
                title: 'Firebase Notification',
                body: "A project state was changed",
                sound: 'default',
                badge: '1'
            }
        };

        return admin.messaging().sendToTopic(topic, payload);
    }
    return true; // signal that we're done, since we're not sending a message
});