-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
Copy pathsocket.ts
50 lines (41 loc) · 1.13 KB
/
socket.ts
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
import { Namespace, Server, Socket as IOSocket } from 'socket.io';
export class Socket {
io: Server;
constructor(httpServer: any) {
this.io = new Server(httpServer, {
/* options */
});
this.init();
}
private init = () => {
this.io.use(async (socket, next) => {
try {
if (socket.handshake.auth.token === 'aa') {
next();
} else {
const err = new Error('unauthorized');
next(err);
}
} catch (e) {
next(new Error('unauthorized'));
}
});
};
public createNamespace = (spaceName: string): Namespace => {
return this.io.of('/' + spaceName);
};
public onConnect = (space: Namespace, cb: (socket: IOSocket) => void) => {
space.on('connection', (socket: IOSocket) => {
cb(socket);
});
};
public joinRoom = (room: string, socket: IOSocket) => {
socket.join(room);
};
public emitToRoomInSpace = (name: string, space: Namespace, room: string, data: any) => {
space.to(room).emit(name, data);
};
public emitToSpace = (name: string, space: Namespace, data: any) => {
space.emit(name, data);
};
}