-
Notifications
You must be signed in to change notification settings - Fork 0
/
request-handler-store.ts
56 lines (45 loc) · 1.54 KB
/
request-handler-store.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
import { Request } from "./request.ts";
import { TypeGuards } from "./type-guards.ts";
import { RequestConstructor, RequestHandler } from "./types.ts";
export class RequestHandlerStore {
private readonly _handlers: Map<symbol, RequestHandler> = new Map();
public add<TRequest extends Request>(
constructor: RequestConstructor<TRequest>,
handler: RequestHandler<TRequest>,
) {
const { name, requestTypeId } = constructor;
if (this._handlers.has(requestTypeId)) {
throw new Error(`Handler for ${name} already exists`);
}
this._handlers.set(
requestTypeId,
handler as RequestHandler,
);
}
public get<TRequest extends Request>(
request: TRequest,
): RequestHandler<TRequest> {
if (!TypeGuards.isRequest(request)) {
throw new Error(`Not a valid request type`);
}
const { name, requestTypeId } = request.constructor;
const foundHandler = this._handlers.get(requestTypeId);
if (foundHandler == null) {
throw new Error(`No handler found for request, ${name}`);
}
return foundHandler;
}
public remove<TRequest extends Request>(
constructor: RequestConstructor<TRequest>,
handler: RequestHandler<TRequest>,
): void {
const { name, requestTypeId } = constructor;
const foundHandler = this._handlers.get(requestTypeId);
if (foundHandler !== handler) {
throw new Error(`No handler found for request, ${name}`);
}
if (!this._handlers.delete(requestTypeId)) {
throw new Error(`Could not remove handler for request, ${name}`);
}
}
}