嗨,我正在开发一个通知系统,但是我在删除处理后的通知数据时遇到了问题。onWrite事件侦听器被触发两次,导致两个通知。
你能帮我找个工作吗?这样onWrite事件侦听器就不会被触发两次?删除处理过的数据是很重要的。
exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */
return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });
      //Deletes processed notification
      console.log("Removing notification");
      const getNotificationPromise = admin.database().ref(`/notification/message/${recipientUid}/${senderUid}`).once('value');
      return Promise.all([getNotificationPromise]).then(results => {
        const notificationSnapshot = results[0];
        toRemove.push(notificationSnapshot.ref.remove());
        console.log("Removing tokens.")
        return Promise.all(toRemove);
      });
      //return Promise.all(tokensToRemove);
    });
});
})发布于 2017-08-18 20:47:19
如果有人仍对此感到困惑,as firebase-功能v0.5.9 ;您可以使用onCreate()、onUpdate()或onDelete()。
npm install --save firebase-functions 此外,firebase文档和示例中也提到,如果您使用的是onWrite(),正如道格前面所解释的那样,该函数将为该节点上的所有事件触发,即写入、更新或删除。因此,您应该检查,以确保您的函数不会卡在循环中。类似于:
   //if data is not new 
    if (event.data.previous.exists()) {return}
    // Exit when the data is deleted; needed cuz after deleting the node this function runs once more.
    if (!event.data.exists()) {return}干杯。
https://stackoverflow.com/questions/43131416
复制相似问题