每当添加新帖子时,我都会尝试将通知推送到 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
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句