gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:57 26 4
gpt4 key购买 nike

每当添加新帖子时,我都会尝试将通知推送到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com