MessageHandlerRegistry.ts
1.43 KB
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 { Connection } from "../connection/Connection";
import { User } from "../user/User";
import { loginHandler } from "./handler/loginHandler";
import { roomChatHandler } from "./handler/roomChatHandler";
import { roomJoinHandler } from "./handler/roomJoinHandler";
import { roomLeaveHandler } from "./handler/roomLeaveHandler";
import { Message, MessageType } from "./types";
export class MessageHandlerRegistry {
static registerHandlers(connection: Connection) {
this.registerHandler(connection, MessageType.LOGIN, loginHandler);
this.registerHandlerAuthed(
connection,
MessageType.ROOM_JOIN,
roomJoinHandler
);
this.registerHandlerAuthed(
connection,
MessageType.ROOM_LEAVE,
roomLeaveHandler
);
this.registerHandlerAuthed(
connection,
MessageType.ROOM_CHAT,
roomChatHandler
);
}
private static registerHandler<T extends Message>(
connection: Connection,
typeName: string,
handler: (connection: Connection, message: T) => void
) {
connection.socket.on(typeName, (message: T) => {
handler(connection, message);
});
}
private static registerHandlerAuthed<T extends Message>(
connection: Connection,
typeName: string,
handler: (user: User, message: T) => void
) {
connection.socket.on(typeName, (message: T) => {
if (connection.user !== undefined) {
handler(connection.user, message);
}
});
}
}