-
Notifications
You must be signed in to change notification settings - Fork 2
/
socket.js
43 lines (41 loc) · 1009 Bytes
/
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
const io = require("socket.io");
const users = require("./users");
/**
* Initialize when a connection is made
* @param {SocketIO.Socket} socket
*/
function initSocket(socket) {
let id;
socket
.on("init", async () => {
id = await users.create(socket);
socket.emit("init", { id });
})
.on("request", data => {
const receiver = users.get(data.to);
if (receiver) {
receiver.emit("request", { from: id });
}
})
.on("call", data => {
const receiver = users.get(data.to);
if (receiver) {
receiver.emit("call", { ...data, from: id });
} else {
socket.emit("failed");
}
})
.on("end", data => {
const receiver = users.get(data.to);
if (receiver) {
receiver.emit("end");
}
})
.on("disconnect", () => {
users.remove(id);
console.log(id, "disconnected");
});
}
module.exports = server => {
io.listen(server, { log: true }).on("connection", initSocket);
};