-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
49 lines (47 loc) · 1.64 KB
/
socket.js
File metadata and controls
49 lines (47 loc) · 1.64 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
const Notification = require('./Models/notification');
let ioInstance;
let onlineUsers = new Map();
const initsocket = (io) => {
ioInstance = io;
io.on('connection',(socket)=>{
console.log('connected',socket.id)
socket.on("join",(userId)=>{
onlineUsers.set(userId,socket.id);
console.log(`User ${userId} is online.`);
})
socket.on("disconnect",()=>{
for(let [key,value] of onlineUsers ){
if(value === socket.id){
onlineUsers.delete(key)
break;
}
}
console.log('User disconnected:', socket.id);
})
})
}
const notify = async(notification) => {
if(!ioInstance){
return;
}
try {
// Fetch the notification with populated data
const populatedNotification = await Notification.findById(notification._id)
.populate("sender", "username profilePicture") // Populate recipient with selected fields
.exec();
if (!populatedNotification) {
console.error("Notification not found");
return;
}
console.log(populatedNotification.recipient.toString());
const recipientSocketId = onlineUsers.get(populatedNotification.recipient.toString());
console.log(onlineUsers);
if (recipientSocketId) {
ioInstance.to(recipientSocketId).emit("newNotification", populatedNotification);
console.log(populatedNotification.type)
}
} catch (error) {
console.error("Error populating notification:", error);
}
};
module.exports = {initsocket,notify}