MessageHandlerRegistry.ts
1.73 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
51
52
53
54
55
56
57
58
59
60
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, MessageResponse, 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,
S extends Message | undefined
>(
connection: Connection,
typeName: string,
handler: (connection: Connection, message: T) => MessageResponse<S>
) {
connection.socket.on(typeName, (message: T, callback: Function) => {
const response = handler(connection, message);
callback(response);
});
}
private static registerHandlerAuthed<
T extends Message,
S extends Message | undefined
>(
connection: Connection,
typeName: string,
handler: (user: User, message: T) => MessageResponse<S>
) {
connection.socket.on(typeName, (message: T, callback: Function) => {
if (connection.user !== undefined) {
const response = handler(connection.user, message);
callback(response);
} else {
callback({ ok: false });
}
});
}
}