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

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

最佳答案

你做错了两件事:

  • 现在,只要在 /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
});

关于node.js - 确定是否向 Firebase 实时数据库添加或删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677506/

相关文章:

swift - 在TableView Swift 4中显示Firebase数据

Android 通知操作按钮点击监听器

javascript - winston : How to get logging with timestamp at the front

javascript - 无法获取 Node js错误

android - 仅使用 "web app"方法将 Firebase 添加到我的 Cordova 应用程序是否可行?

android - 如何在其他安装了我的 android 应用程序的手机上单击按钮时发送我的 android 应用程序的通知

iphone - 服务器到客户端的消息传递能否依赖 APNS?

javascript - 如何在 mongodb 中创建动态文档键

node.js - 使用 join-monster 库 (GraphQL) 对根查询字段进行分页

firebase - 必须向文本小部件提供非空字符串。 'package:flutter/src/widgets/text.dart' : Failed assertion: line 370 pos 10: 'data != null'