Send Push Notifications from Cloud Functions to topic and avoid current user

There are many tutorials about how to send push notifications from Firebase Cloud Functions, so that i going to write a short brief about this in an example.


exports.gameMessageNotification = functions.firestore.document('games/{gameId}/messages/{messageId}').onCreate((change, context) =>{

	const topic = "GameTopic-" + change.after.id
        const newValue    = change.data()

	const notificationContent = {
              data: {
                  type:         "GAME_NEW_MESSAGE",
                  title:        "Title of your notifications",
                  body:         "Body of your notifications,
                  authorId:     newValue.authorId,
                  authorAvatar: newValue.avatar,
                  clickAction:  "OPEN_CHAT_GAME",
                  channelId:    "NOTIFICATION-CHANNEL-GAME-NEW-MESSAGE"
              }		
        };

	return admin.messaging().sendToTopic(topic, notificationContent).then(result => {
	     console.log("Notification sent Game Topic: " + topic);
	     return result
	});
	
});

Pay attention in the payload of notification, only contain «data» object. In this way we always will receive our push notification in onMessageReceived() method of the FirebaseMessagingService().

Now, as to avoid current user in topics notification currently there is no «official» way. Then we have to do it mannually.

In our method onMessageReceived() we have to check if current user logged in android device is different to author user of notification.



override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        super.onMessageReceived(remoteMessage)
        remoteMessage?.let { rMessage ->
            rMessage.data.let {
                if(it.containsKey(PARAM_TYPE)){
                    when(it[PARAM_TYPE]){
                        "GAME_NEW_MESSAGE" -> showGameMessageChatNotification(it["title"], it["body"], it["channelId"], it["clickAction"], it["authorAvatar"], it["authorId"])
                        else  -> showDefaultNotification(rMessage.notification!!.title, rMessage.notification!!.body)
                    }
                }
            }
        }
    }

Write A Comment