I am totally new to Firebase Cloud Functions (2 days exposure). I am trying to send notifications to ALL users of my app when Firebase Database detects that new data has been added. Here is what I have so far:
exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {
const snapshot = event.data;
var str = snapshot.child("name").val();
console.log(str);
if (snapshot.previous.val()) {
return 0;
}
if (snapshot.val().name != "ADMIN") {
return 0;
}
const text = snapshot.val().text;
const payload = {
notification: {
title: snapshot.name,
body: ""
}
}
//return admin.messaging().sendToDevice(tokens, payload);
});
I know the code is in a state of mess right now, its due to a couple of copy and testing from various tutorial sites. I can succesfully get the data's name from console.log but am unable to send notification to ALL users.
I am aware that most use tokens and device IDs. But is there any easier way to send to each and every one of my users ? And do I need to add any java codes for my app for this notification to work ?
EDIT 1: Following Peter's suggestions, I have updated my functions:
exports.sendNotification = functions.database.ref("/uploads/{pushId}").onCreate(event => {
const snapshot = event.data;
var str = snapshot.child("name").val();
console.log(str);
if (snapshot.previous.val()) {
console.log("RETURN 1");
return 0;
}
const payload = {
notification: {
title: str,
body: ""
}
}
return admin.messaging().sendToTopic("Users", payload)
.then(function(response){
console.log("Notification sent ", response);
})
.catch(function(error){
console.log("Error sending notification: ", error);
});
});
I have also added the following java to my code:
FirebaseMessaging.getInstance().subscribeToTopic("Users");
Problem I am having now is that on the Firebase console it says that the notification is being sent successfully, but on my phone I am not receiving anything. Is it a must to use the onMessageReceived method in my case ?
One thing I noticed is that the above statement is being called each time the app launches. Will this effect the result in any way ?