Firebase为removeValue操作发送通知

时间:2018-03-22 06:26:57

标签: javascript firebase firebase-cloud-messaging

所以我的应用程序中有一项功能,用户可以发布或删除任何警报。如果发布了新警报,则其他用户必须收到有关该警报的通知。将新数据添加到数据库时,Firebase推送通知很有效但如果已删除帖子(dataRef.child(root_child).removeValue();),它仍然会向用户发送不需要的通知。如何处理这种情况?

index.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotificationAlert = functions.database.ref(`AlertPost/{pushId}`).onWrite(event => {
const getDeviceTokensPromise = admin.database().ref(`/Token/token_no`).once('value');
  const getBody=admin.database().ref(`/AlertPost`).once('value');
  var title_input='You have a new Alert';
  var contentAlert = event.data.val();
  var body_input=contentAlert.description;
  //const tokensSnapshot = results[0];

  return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
  const tokensSnapshot = results[0];
  const notify=results[1];

  if (!tokensSnapshot.hasChildren()) {
    return console.log('There are no notification tokens to send to.');
  }
  console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
  var contentAlert = event.data.val();

  // Notification details.
  const payload = {
    data: {
      title: title_input,
      body: body_input
      //icon: follower.photoURL
    },
    notification: {
      title: title_input,
      body: body_input
    }

  };

  const tokens = Object.keys(tokensSnapshot.val());

  //token_send(admin,tokensSnapshot,tokens,payload,title_input);

  // Send notifications to all tokens.
  return admin.messaging().sendToDevice(tokens, payload).then(response => {
    console.log("Successfully sent message:", response);
    // For each message check if there was an error.
    const tokensToRemove = [];
    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') {
          tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
        }
      }
    });

    return Promise.all(tokensToRemove);
  });

});


});

1 个答案:

答案 0 :(得分:1)

您可以检查事件DataSnapshot的先前值是否已被删除。有关详细信息,请查看此documentation

source export.sh

您也可以查看此SO post以供参考。