Repository navigation
Expand file tree
/
Copy pathfirebase_functions_code.js
More file actions
59 lines (51 loc) · 2.12 KB
/
Copy pathfirebase_functions_code.js
File metadata and controls
59 lines (51 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
/**
* Triggered when a new message is created in any chat.
* Sends an FCM notification to the receiver.
*/
exports.onTextMessageCreated = functions.firestore
.document('chats/{chatId}/messages/{messageId}')
.onCreate(async (snapshot, context) => {
const messageData = snapshot.data();
const chatId = context.params.chatId;
const messageId = context.params.messageId;
const senderId = messageData.senderId;
const receiverId = messageData.receiverId;
const text = messageData.text;
try {
// 1. Fetch receiver's FCM token
const receiverDoc = await admin.firestore().collection('users').doc(receiverId).get();
if (!receiverDoc.exists) return null;
const receiverData = receiverDoc.data();
const fcmToken = receiverData.fcmToken;
if (!fcmToken) return null;
// 2. Fetch sender's name
const senderDoc = await admin.firestore().collection('users').doc(senderId).get();
const senderName = senderDoc.exists ? senderDoc.data().displayName : "Someone";
// 3. Prepare FCM payload
const payload = {
notification: {
title: senderName,
body: text.length > 50 ? text.substring(0, 47) + "..." : text,
},
data: {
senderId: senderId,
receiverId: receiverId,
chatId: chatId,
messageId: messageId,
type: "text",
click_action: "FLUTTER_NOTIFICATION_CLICK",
},
token: fcmToken,
};
// 4. Send notification
await admin.messaging().send(payload);
console.log(`Notification sent to ${receiverId} from ${senderId}`);
return null;
} catch (error) {
console.error('Error sending notification:', error);
return null;
}
});