实时数据库功能不断触发

时间:2018-06-12 15:54:24

标签: node.js firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我为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,每个值更改都会发送另一个推送通知。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我会尝试这样的事情:

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

答案 1 :(得分:1)

onUpdate()

  

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

当您将其更新为"否"它会发送通知,当您将其更新为" yes"它还会发送通知。

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

相关问题