所以我的应用程序中有一项功能,用户可以发布或删除任何警报。如果发布了新警报,则其他用户必须收到有关该警报的通知。将新数据添加到数据库时,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);
});
});
});
答案 0 :(得分:1)