您好,我正在开发一个通知系统,但我无法删除已处理的通知数据。 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);
});
});
})
最佳答案
这是一个常见的错误。您正在写回到函数首次触发时匹配的同一数据库位置(通过删除数据)。这意味着删除将再次触发该功能以处理第二次更改。这是目前预期的行为。
您需要想出一种方法来检测第二次写入是为了响应数据删除而发生的。另外,你目前在你的职能上做了太多的工作。无需在 '/notification/message/{recipientUid}/{senderUid}'
处读取数据库的值 - 它已经在传递给函数的事件中传递给您。务必read the docs about database triggers .您可以通过检查事件数据并提前返回(如果为 null,这意味着它已被删除)来了解该函数是否被第二次触发。
此外,如果您正在处理单个 promise ,则不需要 Promise.all() 。只需对单个 promise 使用 then() 以继续处理,或从 then() 返回单个 promise 。
您可能想查看一些 sample code显示数据库触发器。
关于node.js - Cloud Functions for Firebase 数据库 onWrite 触发了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43131416/