|
1 | 1 | import { HttpServer } from '@nestjs/common';
|
2 | 2 | import { RequestMethod } from '@nestjs/common/enums/request-method.enum';
|
3 | 3 |
|
| 4 | +/** |
| 5 | + * Ensures (via satisfies) there's a mapping between the RequestMethod enum and the HttpServer interface. |
| 6 | + * @note This is a compile-time check, so if the interface changes, the compiler will complain. |
| 7 | + * This is to resolve a case where a new RequestMethod is added, but the RouterMethodFactory is not updated. |
| 8 | + */ |
| 9 | +const RequestMethodMap = { |
| 10 | + [RequestMethod.GET]: 'get', |
| 11 | + [RequestMethod.POST]: 'post', |
| 12 | + [RequestMethod.PUT]: 'put', |
| 13 | + [RequestMethod.DELETE]: 'delete', |
| 14 | + [RequestMethod.PATCH]: 'patch', |
| 15 | + [RequestMethod.ALL]: 'all', |
| 16 | + [RequestMethod.OPTIONS]: 'options', |
| 17 | + [RequestMethod.HEAD]: 'head', |
| 18 | + [RequestMethod.SEARCH]: 'search', |
| 19 | +} as const satisfies Record<RequestMethod, keyof HttpServer>; |
| 20 | + |
4 | 21 | export class RouterMethodFactory {
|
5 | 22 | public get(target: HttpServer, requestMethod: RequestMethod): Function {
|
6 |
| - switch (requestMethod) { |
7 |
| - case RequestMethod.POST: |
8 |
| - return target.post; |
9 |
| - case RequestMethod.ALL: |
10 |
| - return target.all; |
11 |
| - case RequestMethod.DELETE: |
12 |
| - return target.delete; |
13 |
| - case RequestMethod.PUT: |
14 |
| - return target.put; |
15 |
| - case RequestMethod.PATCH: |
16 |
| - return target.patch; |
17 |
| - case RequestMethod.OPTIONS: |
18 |
| - return target.options; |
19 |
| - case RequestMethod.HEAD: |
20 |
| - return target.head; |
21 |
| - case RequestMethod.GET: |
22 |
| - return target.get; |
23 |
| - default: { |
24 |
| - return target.use; |
25 |
| - } |
| 23 | + const methodName = RequestMethodMap[requestMethod]; |
| 24 | + const method = target[methodName]; |
| 25 | + if (!method) { |
| 26 | + // There should probably be a warning message in this case |
| 27 | + return target.use; |
26 | 28 | }
|
| 29 | + return method; |
27 | 30 | }
|
28 | 31 | }
|
0 commit comments