-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathsocketServer.js
38 lines (32 loc) · 968 Bytes
/
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
const jwt = require("jsonwebtoken");
let users = [];
const authSocket = (socket, next) => {
let token = socket.handshake.auth.token;
if (token) {
try {
const decoded = jwt.verify(token, process.env.TOKEN_KEY);
socket.decoded = decoded;
next();
} catch (err) {
next(new Error("Authentication error"));
}
} else {
next(new Error("Authentication error"));
}
};
const socketServer = (socket) => {
const userId = socket.decoded.userId;
users.push({ userId, socketId: socket.id });
socket.on("send-message", (recipientUserId, username, content) => {
const recipient = users.find((user) => user.userId == recipientUserId);
if (recipient) {
socket
.to(recipient.socketId)
.emit("receive-message", userId, username, content);
}
});
socket.on("disconnect", () => {
users = users.filter((user) => user.userId != userId);
});
};
module.exports = { socketServer, authSocket };