确定是否向Firebase实时数据库添加或删除数据 [英] Determining whether data is added or deleted to Firebase realtime database

查看:27
本文介绍了确定是否向Firebase实时数据库添加或删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当添加新帖子时,我都试图将通知推送到android应用.但是,只要数据更改"(即即使删除了我不需要的帖子),通知就会到达.我如何设置条件,以便FCM仅在添加帖子后才发送通知.这是我的index.js文件

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

推荐答案

您做错了两件事:

  • 现在,只要在/promos 下写入任何数据,就会触发您的函数.您希望每当编写特定促销时触发它:/promo/{promoid} .

  • 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}.

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

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

所以更接近这个:

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

这篇关于确定是否向Firebase实时数据库添加或删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆