-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketHandler.js
67 lines (57 loc) · 2 KB
/
socketHandler.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
import { Server } from 'socket.io';
import { createAdapter } from '@socket.io/cluster-adapter';
import { setupWorker } from '@socket.io/sticky';
export default class {
constructor(server) {
this.io = new Server(server);
this.io.adapter(createAdapter())
setupWorker(this.io)
this.init();
}
init() {
this.io.on("connection", socket => {
console.log("🔌 Socket connected")
// Join rooms based on user's Chat Ids
socket.handshake.query.chatList.split(",").map(id => socket.join(id))
// Join user id room to communicate updates to client app
const userId = socket.handshake.query.user;
socket.join(userId);
socket.on("messageSent", (messageData) => {
this.io.to(messageData.chat).emit("messageSent", messageData.chat);
})
socket.on("joinRooms", (roomList) => {
// join all listed rooms (ignores rooms that this socket has already joined)
roomList.forEach(room => socket.join(room))
})
socket.on("leaveRoom", (room) => {
socket.leave(room)
})
socket.on("appOpened", (user) => {
this.io.to(user).emit("appOpened")
})
socket.on("notificationsUpdated", (user) => {
this.io.to(user).emit("notificationsUpdated")
})
socket.on("disconnect", () => {
socket.disconnect();
})
})
}
/**
* Send user a simple event notif
* @param {String} id the user's id
* @param {String} event the name of the event
*/
sendUserEvent(id, event) {
this.io.to(id).emit(event);
}
/**
* Send user an event and data
* @param {String} id the user's id
* @param {any} data the data to send
* @param {String} event the event to emit
*/
sendDataEvent(id, data, event) {
this.io.to(id).emit(event, data)
}
}