-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.js
85 lines (71 loc) · 2.29 KB
/
socket.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
import { Server } from "socket.io";
import { createServer } from "http";
import { SUGGEST_FOLLOWERS_TASK_KEY, SUGGESTED_USERS } from "./config.js";
import { verifyToken, validateCors } from "./utils/middlewares.js";
import { createError } from "./utils/error.js";
import { clearGetAllIntervallyTask } from "./utils/schedule-tasks.js";
import cookie from "cookie";
import { CLIENT_ORIGIN } from "./constants.js";
export default (app, port = process.env.PORT || 8800) => {
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: validateCors,
path: "/soshare"
});
app.set("socketIo", io);
io.use((socket, next) => {
const _cookie = socket.request.headers.cookie;
const cookies = _cookie
? typeof _cookie === "string"
? cookie.parse(_cookie)
: _cookie
: undefined;
try {
if (cookies) {
verifyToken(
{
cookies
},
undefined,
next
);
socket.handshake.withCookies = true;
}
next();
} catch (err) {
if (socket.handshake.userId) socket.disconnect();
next(cookies ? createError(err.message, err.status || 401) : undefined);
}
});
io.on("connection", socket => {
const handleRegUser = (id, cb) => {
if (id) {
socket.handshake[SUGGESTED_USERS] = [];
socket.handshake.userId = id;
socket.join(id);
typeof cb === "function" && cb();
} else socket.emit("bare-connection");
};
if (socket.handshake.withCookies) {
!socket.handshake.userId && io.emit("register-user");
socket.on("register-user", handleRegUser);
} else {
socket.emit("bare-connection");
}
socket.on("disconnect-suggest-followers-task", () =>
clearGetAllIntervallyTask(socket, SUGGEST_FOLLOWERS_TASK_KEY)
);
socket.on("disconnect", () => {
socket.removeAllListeners();
socket.leave(socket.handshake.userId);
clearGetAllIntervallyTask(socket, SUGGEST_FOLLOWERS_TASK_KEY);
io.removeListener("register-user", handleRegUser);
delete socket.handshake[SUGGESTED_USERS];
delete socket.handshake.withCookies;
delete socket.handshake.userId;
});
});
httpServer.listen(port, () => {
console.log(`App listening on port ${port}`);
});
};