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 }) }) }) })
Thanks bro
Shows 400 error. Doesn’t work , can you check the code. Thanks
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://accounts.binance.com/en-IN/register?ref=UM6SMJM3
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.