Reputation: 1
I want to send a notification when realtime-database have new data to some user who has specific data in Firebase Firestore.
Sample of data that has a relation to the user.
and the user has the group what he followed it.
Firebase Firestore - user data
as of now, the specific data is the group name.
easily, send a notification to users who have the same group name as the poster group name
Upvotes: 0
Views: 242
Reputation: 26236
Instead of searching Cloud Firestore for users to notify, you should employ Firebase Cloud Messaging instead. This allows you to subscribe each user to a topic corresponding to the groups they are in.
Because you will need to subscribe each relevant user to their corresponding notification topics, this won't be a simple "drop-in and it works" solution. Consult the documentation for your targeted platforms on how to do this.
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
export const notifyGroupsOfNewPost = functions.database.ref("/Poster/{postId}").onCreate(async (snapshot, context) => {
/* avoid using `snapshot.val()` unless you need all of the data at once */
const postGroups = snapshot.child("Groups").val(); // assumed to be parsed as an array, make sure to handle non-array values gracefully
if (postGroups === null) {
throw new Error('Groups of new post missing');
}
return Promise.all(postGroups.map((group) => {
const message = {
/* note: only send data used for creating the notification message,
the rest of it can be downloaded using the SDK once it's needed */
data: {
Impact: snapshot.child("Impact").val(),
Subject: snapshot.child("Subject").val(),
TT: snapshot.child("TT").val()
},
topic: group /* you could also use `${group}-newpost` here */
};
return admin.messaging().send(message)
.then((messageId) => {
console.log(`Successfully notified the ${group} group about new post #${snapshot.key} (FCM #{$messageId})`);
})
.catch((error) => {
console.error(`Failed to notify the ${group} group about new post #${snapshot.key}:`, error);
});
});
});
Upvotes: 1