-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.ts
59 lines (49 loc) · 1.31 KB
/
websocket.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
51
52
53
54
55
56
57
58
59
import * as socketio from 'socket.io';
import * as socketioJwt from 'socketio-jwt-auth';
import { Server } from 'http';
import { Client } from './src/Client';
import { Connection } from './src/Connection';
export function attachWss(httpServer: Server, {
rooms,
pubKey
}) {
const io = socketio(httpServer);
io.use(
socketioJwt.authenticate({
secret: pubKey,
algorithm: 'RS256'
}, (payload, cb) => {
if (!payload.user_id) {
return cb('Malformed token.');
}
return cb(null, payload);
})
);
io.on('connection', (socket) => {
const connection = new Connection(socket.request.user.user_id, socket);
const client = new Client(connection);
socket.on('join', (roomid) => {
onRoom(roomid, (room) => client.join(room));
});
socket.on('leave', (roomid) => {
onRoom(roomid, (room) => client.leave(room));
});
socket.on('data', (roomid, data) => {
onRoom(roomid, (room) => room.onMessage(connection, data));
});
socket.on('whoami', (cb) => {
if (typeof cb === 'function') {
cb(connection.uid);
}
});
socket.on('disconnect', () => {
client.leaveAll();
});
});
function onRoom(roomid, cb) {
const room = rooms.get(roomid);
if (room !== undefined) {
cb(room);
}
}
}