所以我的应用程序中有一个功能,用户可以在其中发布或删除任何警报。如果发布了新警报,其他用户必须收到有关该警报的通知。当将新数据添加到数据库时,Firebase推送通知效果很好,但如果帖子已被删除(dataRef.child(root_child).removeValue();
(,它仍然会向用户发送不需要的通知。如何处理这种情况?
索引.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);
});
});
});
您可以检查事件 DataSnapshot 的先前值是否已被删除。有关详细信息,请查看此文档。
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite((event) => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
});
您也可以查看此SO帖子以供参考。