【问题标题】:Realtime database function triggers constantly实时数据库功能不断触发
【发布时间】: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


【解决方案1】:

我会尝试这样的:

exports.sendNewPostNotif = functions.database.ref('/rollo').onWrite((change, context) => {

  const newData = change.after.val();
  const oldData = change.before.val();

      const payload = {
        notification: {
            title: 'Push triggered!',
            body: "Push text",
            sound: "default"
        }
    };

      const options = {
        priority: "high",
        timeToLive: 60 * 10 * 1
    };
  if (newData != oldData && newData == 'yes') {
    return admin.messaging().sendToTopic("notifications", payload, options);
  }
});

【讨论】:

    【解决方案2】:

    onUpdate():

    在实时数据库中更新数据时触发。

    当您将其更新为“否”时,它会发送通知,当您将其更新为“是”时,它也会发送通知。

    https://firebase.google.com/docs/functions/database-events

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 2022-11-21
      • 2014-09-12
      • 1970-01-01
      • 2018-10-12
      相关资源
      最近更新 更多