【发布时间】:2018-11-22 02:17:38
【问题描述】:
我已经为 Firebase 实时数据库触发器部署了一个 JS 函数。在其操作中,它应该仅在数据库中的值更新时发送推送通知,这非常简单:
{
"rollo" : "yes"
}
如果值更改为 yes,则应触发通知。如果它变为“否”,那么它应该什么都不做。这是JS函数:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNewPostNotif = functions.database.ref('/rollo').onUpdate((change, context) => {
console.log('Push notification event triggered');
const beforeData = change.before.val();
const payload = {
notification: {
title: 'Push triggered!',
body: "Push text",
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60 * 10 * 1
};
return admin.messaging().sendToTopic("notifications", payload, options);
});
此外,即使我设置了 TTL,每次值更改都会发送另一个推送通知。
有什么想法吗?
【问题讨论】:
-
如果我明白你在问什么,以及发生了什么问题......现在它会向数据库发送每次更改的通知,而不仅仅是当它变为“是”时......但现在当它变为“否”时它也会发送......而你不希望那样......对吗?我看到你有
const beforeData = change.before.val();,但你从来没有用它做任何事情。因此,您的解决方案将是一个简单的if (beforeData === 'no' && afterData === 'yes')条件...。这就是您要找的吗? -
@JeremyW 你应该发表你的评论作为答案。
标签: node.js firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions