我已经为Firebase实时数据库触发器部署了JS函数。在操作中,它应该仅在数据库中的值更新时发送推送通知,这简直是简单的:
{
"rollo" : "yes"
}
如果值更改为yes,则应触发通知。如果变为“否”,则它什么也不做。这是JS函数:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNewPostNotif = functions.database.ref('/rollo').onUpdate((change, context) => {
console.log('Push notification event triggered');
const beforeData = change.before.val();
const payload = {
notification: {
title: 'Push triggered!',
body: "Push text",
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60 * 10 * 1
};
return admin.messaging().sendToTopic("notifications", payload, options);
});
同样,即使我已设置TTL,每次更改值都会发送另一个推送通知。
有任何想法吗?
最佳答案
我会尝试这样的事情:
exports.sendNewPostNotif = functions.database.ref('/rollo').onWrite((change, context) => {
const newData = change.after.val();
const oldData = change.before.val();
const payload = {
notification: {
title: 'Push triggered!',
body: "Push text",
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60 * 10 * 1
};
if (newData != oldData && newData == 'yes') {
return admin.messaging().sendToTopic("notifications", payload, options);
}
});