How To Create Notification Service For My Chat Application?
Solution 1:
For sending push notifications to clients you would need to either run an app serve instance (for example on Google App Engine) or even easier now that there is Firebase functions, via a function. In simple words you need to have a piece of code running on a server which reacts to your requests and sends the notification.
I have found Firebase functions to be the easiest way to do that since you are already using Firebase Database. You need to write your functions and then deploy them.
--> firebase deploy --only functions
Your functions can be triggered whenever new data is written (onCreate()), updated or even removed from database. (Imagine, you write your functions such that it triggers whenever a new message is written to your database at "messages" node).
Also, you need to store users unique messaging "token"s generated client side in your database because you need it later in your function to send the notification. In your function, you need to retrieve that token from database and send the notification via SDK. Here is a simplified code of what I explained:
//your imports ; see sample linked below for a complete example//imagine your functions is triggered by any new write in "messages" node in your databaseexports.sendNotification = functions.database.ref('/messages/{keyId}').onWrite(
//get the token that is already saved in db then ; const payload = {
notification: {
title: 'You have a new follower!',
body: `${follower.displayName} is now following you.`,
icon: follower.photoURL
}
};
admin.messaging().sendToDevice(tokens, payload); //which is a promise to handle
});
For sample on sending notification via Firebase functions see Here. For Firebase function samples see Here. More on Firebase functions and triggers see here.
For some more explanation see here (keep in mind this was written before Firebase functions) and so it assumes you are deploying it to an app server instance. Also, here is more information on using cloud functions (Firebase functions) for sending notifications.
Post a Comment for "How To Create Notification Service For My Chat Application?"