MessageHandler.ts
882 Bytes
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
import { Connection } from "../connection/Connection";
import {
ServerInboundMessage,
ServerInboundMessageMap,
ServerResponse,
} from "../../common/index";
type ServerHandlerMap<T> = {
[Key in keyof ServerInboundMessageMap]?: (
connection: Connection,
message: ServerInboundMessage<Key>,
scope: T
) => ServerResponse<Key>;
};
export class HandlerMap<T> {
private scope: T;
private handlers: ServerHandlerMap<T>;
constructor(scope: T, handlers: ServerHandlerMap<T>) {
this.scope = scope;
this.handlers = handlers;
}
public handle(
type: keyof ServerInboundMessageMap,
connection: Connection,
message: any,
callback: Function
): boolean {
const handler = this.handlers[type];
if (!handler) return false;
const response = handler(connection, message, this.scope);
callback(response);
return true;
}
}