I am building a multi group (Group 1, Group 2, Group 3, etc.) chat app with FlutterFlow and Firebase, where every authenticated user [uid] has the ability to join a chat group from a listview. By tapping on a group, the user will join the chat group and the group chat will open. The users collection [uid] will be added to the [GroupMember] array of users in the WatchNotification collection. Each document in the WatchNotification collection is a group. Now the user can comment in that chat group. When the user sends the comment, a new document are created in the Messages collection with the [GroupId] from the Group collection, the [SenderId] from the Authenticated user [uid] and the [Message] from the TextField in the Widget State. A push notifications must be send with Cloud Functions to all the users in that specific chat group, except to the sender, when the document are created. Here is the Cloud Function code that I’m using, but it is not working. Can anyone help me to modify this Cloud Function code to get it to work?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code
exports.sendPushNotification = functions.firestore.document('Messages/{messageId}').onCreate(async (snapshot, context) => {
const messageData = snapshot.data();
const groupId = messageData.Group; // Where 'Group' field holds the WatchNotification document ID
const senderId = messageData.UID; // Where 'UID' field holds the sender's ID
// Fetch the group members from the WatchNotification document
const groupMembersSnapshot = await admin.firestore().doc(`WatchNotification/${groupId}`).get();
const memberIds = groupMembersSnapshot.data().GroupMembers; // Where 'GroupMembers' is an array of user IDs
// Filter out the sender's ID
const recipientIds = memberIds.filter(memberId => memberId !== senderId);
// Fetch FCM tokens for each recipient
const memberTokens = await Promise.all(recipientIds.map(async (recipientId) => {
const userDoc = await admin.firestore().collection('users').doc(recipientId).get();
return userDoc.data().fcmToken;
}));
// Construct the notification message
const message = {
notification: {
title: 'New Message',
body: 'You have a new message in the group.'
},
tokens: memberTokens
};
// Send the notification using FCM
admin.messaging().sendMulticast(message)
.then((response) => {
console.log('Notifications sent successfully:', response)
})
.catch((error) => {
console.error('Error sending notifications:', error)
});
});