Reputation: 3
I have deployed a JS function for Firebase realtime database triggers. In its operations, it should send a push notification just on value update in the database, which is dead simple:
{
"rollo" : "yes"
}
If value changes to yes it should trigger notification. If it goes to "no" then it should do nothing. Here is the JS function:
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);
});
Also even though I have set TTL, each value change sends another push notification.
Any ideas?
Upvotes: 0
Views: 575
Reputation: 594
I would try something like this:
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);
}
});
Upvotes: 2
Reputation: 80914
onUpdate()
:
triggers when data is updated in the Realtime Database.
When you update it to "no" it will send a notification and when you update it to "yes" it will also send a notification.
https://firebase.google.com/docs/functions/database-events
Upvotes: 1