Updated 30 October 2017
Firebase Cloud Functions are still in their Beta phase but I still think its the best Feature of Firebase, making any things easier for developers. In one of my previous blog, I presented a method to send notification message to a Firebase Notification key if there is a new message for that user. Now I am here to provide you a way to send messages to multiple notification keys or tokens whenever there is a new message for that person or group, whatever the case is for you.
For that firstly lets see our database structure first. So this is the database structure. There are two main sub-sections namely data and messages. The data part contains customer data while the message part contains the messages exchanged between people.As we can not enter single token values under tokens filed because its a json-based database, I used the one defined in Firebase sample i.e. to use token value as key and giving value true against the json value. You can provide any other value if you want.
So now lets move on to writing the event function. So all the process is same just we need a iterator to iterate through all the values in tokens so we are using method Promise.all() The final method I got is as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
exports.sendNotificationsToAll = functions.database .ref("/message/{userId}/{pushId}") .onWrite(event => { const snapshot = event.data; const userId = event.params.userId; if (snapshot.previous.val()) { return; } // Only messages from admin need to be sent to client [In my case] if (snapshot.val().name != "ADMIN") { return; } const text = snapshot.val().text; const payload = { notification: { title: `New message by ${snapshot.val().name}`, body: text ? text.length <= 100 ? text : text.substring(0, 97) + "..." : "" } }; return Promise.all([admin.database().ref(`data/${userId}/tokens`).once('value')]).then(data => { const allTokens = Object.keys(data[0].val()); return admin.messaging().sendToDevice(allTokens, payload); }); }); |
And here you got to send message to multiple tokens whenever a new message is added to the particular sender node.
Source: https://github.com/firebase/functions-samples/tree/master/fcm-notifications
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.