-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocketServer.js
69 lines (56 loc) · 2.05 KB
/
SocketServer.js
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
60
61
62
63
64
65
66
67
68
69
let onlineUsers = []
const addUser = (userId, socketId) => {
!onlineUsers.some(user => user.userId === userId) && onlineUsers.push({ userId, socketId });
}
const removeUser = socketId => {
onlineUsers = onlineUsers.filter(user => user.socketId !== socketId);
};
const getUser = (userId) => {
return onlineUsers.find((user) => user.userId === userId);
};
const findConnectedUser = userId =>
onlineUsers.find(user => user.userId === userId);
const SocketServer = (socket) => {
socket.on('join', (userId) => {
addUser(userId, socket.id);
socket.emit("getusers", onlineUsers);
});
const handler = (sender, receiver, { type, reactionType, post }) => {
const receiverSocket = findConnectedUser(receiver.username);
if (receiverSocket && sender.id != receiver.id) {
io.to(receiverSocket.socketId)
.emit('notificationReceived', {
sender,
receiverUsername: receiver.username,
type,
reactionType,
post,
});
}
};
//#region //!Messages
socket.on("Message", ({ sender, receiver, createdAt, image, chatId, msg }) => {
const user = getUser(receiver);
if (user) {
socket.to(user.socketId)
.emit("MessagetoClient", { sender, receiver, createdAt, chatId, image, msg });
}
});
socket.on('typing', ({ sender, receiver, chatId, status }) => {
const user = getUser(receiver);
if (user) {
socket.to(user.socketId)
.emit("TypingtoClient", { sender, receiver, chatId, status });
}
});
socket.on('like', ({ sender, receiver, reactionType, post }) => {
handler(sender, receiver, { type: 'react', reactionType, post });
});
socket.on('comment', ({ sender, receiver, post }) => {
handler(sender, receiver, { type: 'comment', post });
});
socket.on('disconnect', () => {
removeUser(socket.id);
});
}
export default SocketServer