Firebase provides a bunch of awesome services such as Firestore, Auth, Cloud Storage, Cloud Functions and Cloud Messaging. Learn how to use them in this tutorial course in which we’re making a fully fledged real-time chat app with everything you’d expect like sending images and getting notifications when we receive a new message.

In this part you will learn how to create a Cloud Function in Javascript which will send an FCM message to all of the user’s devices when he/she receives a message from another user. You will also learn how to set everything up on your computer in order for you to be able to upload cloud functions, well, to the cloud.

This post contains all the code that’s been written in this YouTube video.

 

To get the code check out this GitHub repository: https://github.com/ResoCoder/firebase-firestore-chat-app

 

index.js

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();

exports.notifyNewMessage = functions.firestore
    .document('chatChannels/{channel}/messages/{message}')
    .onCreate((docSnapshot, context) => {
        const message = docSnapshot.data();
        const recipientId = message['recipientId'];
        const senderName = message['senderName'];

        return admin.firestore().doc('users/' + recipientId).get().then(userDoc => {
            const registrationTokens = userDoc.get('registrationTokens')

            const notificationBody = (message['type'] === "TEXT") ? message['text'] : "You received a new image message."
            const payload = {
                notification: {
                    title: senderName + " sent you a message.",
                    body: notificationBody,
                    clickAction: "ChatActivity"
                },
                data: {
                    USER_NAME: senderName,
                    USER_ID: message['senderId']
                }
            }

            return admin.messaging().sendToDevice(registrationTokens, payload).then( response => {
                const stillRegisteredTokens = registrationTokens

                response.results.forEach((result, index) => {
                    const error = result.error
                    if (error) {
                        const failedRegistrationToken = registrationTokens[index]
                        console.error('blah', failedRegistrationToken, error)
                        if (error.code === 'messaging/invalid-registration-token'
                            || error.code === 'messaging/registration-token-not-registered') {
                                const failedIndex = stillRegisteredTokens.indexOf(failedRegistrationToken)
                                if (failedIndex > -1) {
                                    stillRegisteredTokens.splice(failedIndex, 1)
                                }
                            }
                    }
                })

                return admin.firestore().doc("users/" + recipientId).update({
                    registrationTokens: stillRegisteredTokens
                })
            })
        })
    })

 

 

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a freelancer and most importantly developer educator, he is set on helping other people succeed in their Flutter app development career.

You may also like

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >