确定是否向Firebase实时数据库添加或删除数据

时间:2017-06-21 13:26:07

标签: node.js firebase push-notification google-cloud-functions

我试图在添加新帖子时将通知推送到Android应用。但是,只要数据被“更改”,通知就会到达。即使删除了我不需要的帖子。我如何设置一个条件,以便FCM仅在添加帖子时发送通知。这是我的index.js文件

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 个答案:

答案 0 :(得分:0)

你做错了两件事:

  • 只要在/promos下写入任何数据,就会触发您的功能。您希望在撰写特定促销时触发它:/promo/{promoid}

  • 您完全无视数据是否已存在:if (!event.data.previous.exists()) {,因此需要将其连接起来。

更接近这一点:

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