-
Notifications
You must be signed in to change notification settings - Fork 1
/
webSocketHandler.js
102 lines (68 loc) · 2.63 KB
/
webSocketHandler.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const WebSocket = require('ws');
const jwt = require("jsonwebtoken");
const { server } = require("./server.config");
const wss = new WebSocket.Server({server: server});
const clients = new Map();
const closureFunc = () => {
wss.on('connection', (ws, req) => {
const cookie = req.headers.cookie;
if (cookie) {
const token = cookie.split("token=")[1].split(";")[0];
jwt.verify(token, process.env.SECRET, function (err, decoded) {
if(err){
console.log(err);
}else{
ws.authUser = decoded.user;
clients.set(String(ws.authUser._id), ws);
}
});
}
ws.on("message", (message) => {
let jsonMessage = {"type": ""}
try {
jsonMessage = JSON.parse(message.toString());
} catch (error) {
console.log(error);
}
const type = jsonMessage.type;
if (type == "CREATE_FRIEND_REQUEST"){
console.log(jsonMessage);
const notification = {
type: "FRIEND_REQUEST_NOTIFICATION",
data: jsonMessage.data
}
cl = clients.get(String(jsonMessage.data.notification.receiver));
if(cl){
cl.send(JSON.stringify(notification))
}
}
if (type == "CREATE_LIKE_NOTIFICATION"){
console.log(jsonMessage);
const notification = {
type: "LIKE_NOTIFICATION",
data: jsonMessage.data
}
cl = clients.get(String(jsonMessage.data.notification.receiver));
if(cl){
cl.send(JSON.stringify(notification))
}
}
if (type == "CREATE_COMMENT_NOTIFICATION"){
console.log(jsonMessage);
const notification = {
type: "COMMENT_NOTIFICATION",
data: jsonMessage.data
}
cl = clients.get(String(jsonMessage.data.notification.receiver));
if(cl){
cl.send(JSON.stringify(notification))
}
}
})
// When the client closes the connection, remove them from the list of connected clients
ws.on('close', (ws) => {
clients.delete(String(ws?.authUser?._id));
});
});
}
module.exports = closureFunc;