-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathcontroller.module.ts
More file actions
69 lines (54 loc) · 1.79 KB
/
Copy pathcontroller.module.ts
File metadata and controls
69 lines (54 loc) · 1.79 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
61
62
63
64
65
66
67
68
69
import { joinPath } from '~/libs/modules/path/path.js';
import { type LoggerModule } from '../logger/logger.js';
import { type ServerApplicationRouteParameters } from '../server-application/server-application.js';
import {
type ControllerAPIHandler,
type ControllerAPIHandlerOptions,
type ControllerModule,
type ControllerRouteParameters
} from './libs/types/types.js';
type Constructor = {
apiPath: string;
logger: LoggerModule;
};
class Controller implements ControllerModule {
#apiPath: string;
#logger: LoggerModule;
#routes: ServerApplicationRouteParameters[] = [];
public constructor({ apiPath, logger }: Constructor) {
this.#logger = logger;
this.#apiPath = apiPath;
}
private async mapHandler(
handler: ControllerAPIHandler,
request: Parameters<ServerApplicationRouteParameters['handler']>[0],
reply: Parameters<ServerApplicationRouteParameters['handler']>[1]
): Promise<void> {
this.#logger.info(`${request.method.toUpperCase()} on ${request.url}`);
const handlerOptions = this.mapRequest(request);
const { payload, status } = await Promise.resolve(handler(handlerOptions));
return await reply.status(status).send(payload);
}
private mapRequest(
request: Parameters<ControllerRouteParameters['handler']>[0]
): ControllerAPIHandlerOptions {
const { body, params, query } = request;
return {
body,
params,
query
};
}
public addRoute(options: ControllerRouteParameters): void {
const { handler, url } = options;
this.#routes.push({
...options,
handler: (request, reply) => this.mapHandler(handler, request, reply),
url: joinPath([this.#apiPath, url])
});
}
public get routes(): ServerApplicationRouteParameters[] {
return this.#routes;
}
}
export { Controller };