@nestia/core 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/lib/decorators/DynamicModule.js.map +1 -1
  2. package/lib/decorators/EncryptedBody.js.map +1 -1
  3. package/lib/decorators/EncryptedController.js.map +1 -1
  4. package/lib/decorators/EncryptedModule.js.map +1 -1
  5. package/lib/decorators/EncryptedRoute.js +0 -2
  6. package/lib/decorators/EncryptedRoute.js.map +1 -1
  7. package/lib/decorators/PlainBody.js.map +1 -1
  8. package/lib/decorators/TypedBody.js.map +1 -1
  9. package/lib/decorators/TypedException.js.map +1 -1
  10. package/lib/decorators/TypedHeaders.js.map +1 -1
  11. package/lib/decorators/TypedParam.js.map +1 -1
  12. package/lib/decorators/TypedQuery.js +1 -5
  13. package/lib/decorators/TypedQuery.js.map +1 -1
  14. package/lib/decorators/TypedRoute.js.map +1 -1
  15. package/lib/decorators/internal/NoTransformConfigureError.js.map +1 -1
  16. package/lib/decorators/internal/get_path_and_querify.js.map +1 -1
  17. package/lib/decorators/internal/get_path_and_stringify.js.map +1 -1
  18. package/lib/decorators/internal/get_text_body.js.map +1 -1
  19. package/lib/decorators/internal/headers_to_object.js.map +1 -1
  20. package/lib/decorators/internal/load_controller.js.map +1 -1
  21. package/lib/decorators/internal/route_error.js.map +1 -1
  22. package/lib/decorators/internal/validate_request_body.js.map +1 -1
  23. package/lib/decorators/internal/validate_request_headers.js.map +1 -1
  24. package/lib/decorators/internal/validate_request_query.js.map +1 -1
  25. package/lib/programmers/PlainBodyProgrammer.js.map +1 -1
  26. package/lib/programmers/TypedBodyProgrammer.js.map +1 -1
  27. package/lib/programmers/TypedExceptionProgrammer.js.map +1 -1
  28. package/lib/programmers/TypedHeadersProgrammer.js.map +1 -1
  29. package/lib/programmers/TypedParamProgrammer.js.map +1 -1
  30. package/lib/programmers/TypedQueryBodyProgrammer.js.map +1 -1
  31. package/lib/programmers/TypedQueryProgrammer.js.map +1 -1
  32. package/lib/programmers/TypedQueryRouteProgrammer.js.map +1 -1
  33. package/lib/programmers/TypedRouteProgrammer.js.map +1 -1
  34. package/lib/programmers/http/HttpAssertQuerifyProgrammer.js.map +1 -1
  35. package/lib/programmers/http/HttpIsQuerifyProgrammer.js.map +1 -1
  36. package/lib/programmers/http/HttpQuerifyProgrammer.js.map +1 -1
  37. package/lib/programmers/http/HttpValidateQuerifyProgrammer.js.map +1 -1
  38. package/lib/programmers/internal/CoreMetadataUtil.js.map +1 -1
  39. package/lib/transform.js.map +1 -1
  40. package/lib/transformers/FileTransformer.js.map +1 -1
  41. package/lib/transformers/MethodTransformer.js +1 -2
  42. package/lib/transformers/MethodTransformer.js.map +1 -1
  43. package/lib/transformers/NodeTransformer.js.map +1 -1
  44. package/lib/transformers/ParameterDecoratorTransformer.js +1 -3
  45. package/lib/transformers/ParameterDecoratorTransformer.js.map +1 -1
  46. package/lib/transformers/ParameterTransformer.js.map +1 -1
  47. package/lib/transformers/TypedExceptionTransformer.js.map +1 -1
  48. package/lib/transformers/TypedRouteTransformer.js +1 -2
  49. package/lib/transformers/TypedRouteTransformer.js.map +1 -1
  50. package/lib/utils/ExceptionManager.js.map +1 -1
  51. package/lib/utils/Singleton.js.map +1 -1
  52. package/lib/utils/SourceFinder.js +1 -3
  53. package/lib/utils/SourceFinder.js.map +1 -1
  54. package/package.json +3 -6
  55. package/src/decorators/DynamicModule.ts +39 -39
  56. package/src/decorators/EncryptedBody.ts +49 -57
  57. package/src/decorators/EncryptedController.ts +38 -38
  58. package/src/decorators/EncryptedModule.ts +79 -79
  59. package/src/decorators/EncryptedRoute.ts +126 -135
  60. package/src/decorators/PlainBody.ts +72 -75
  61. package/src/decorators/TypedBody.ts +59 -60
  62. package/src/decorators/TypedException.ts +89 -89
  63. package/src/decorators/TypedHeaders.ts +69 -70
  64. package/src/decorators/TypedParam.ts +65 -66
  65. package/src/decorators/TypedQuery.ts +246 -253
  66. package/src/decorators/TypedRoute.ts +144 -147
  67. package/src/decorators/internal/EncryptedConstant.ts +4 -4
  68. package/src/decorators/internal/NoTransformConfigureError.ts +8 -8
  69. package/src/decorators/internal/get_path_and_querify.ts +103 -104
  70. package/src/decorators/internal/get_path_and_stringify.ts +91 -94
  71. package/src/decorators/internal/get_text_body.ts +20 -20
  72. package/src/decorators/internal/headers_to_object.ts +13 -13
  73. package/src/decorators/internal/load_controller.ts +51 -51
  74. package/src/decorators/internal/route_error.ts +45 -45
  75. package/src/decorators/internal/validate_request_body.ts +57 -61
  76. package/src/decorators/internal/validate_request_headers.ts +68 -73
  77. package/src/decorators/internal/validate_request_query.ts +56 -59
  78. package/src/index.ts +5 -5
  79. package/src/module.ts +14 -14
  80. package/src/options/INestiaTransformOptions.ts +17 -17
  81. package/src/options/INestiaTransformProject.ts +7 -7
  82. package/src/options/IRequestBodyValidator.ts +20 -20
  83. package/src/options/IRequestHeadersValidator.ts +22 -22
  84. package/src/options/IRequestQueryValidator.ts +20 -20
  85. package/src/options/IResponseBodyQuerifier.ts +25 -25
  86. package/src/options/IResponseBodyStringifier.ts +25 -25
  87. package/src/programmers/PlainBodyProgrammer.ts +52 -56
  88. package/src/programmers/TypedBodyProgrammer.ts +108 -112
  89. package/src/programmers/TypedExceptionProgrammer.ts +72 -76
  90. package/src/programmers/TypedHeadersProgrammer.ts +56 -59
  91. package/src/programmers/TypedParamProgrammer.ts +24 -25
  92. package/src/programmers/TypedQueryBodyProgrammer.ts +56 -57
  93. package/src/programmers/TypedQueryProgrammer.ts +56 -57
  94. package/src/programmers/TypedQueryRouteProgrammer.ts +51 -55
  95. package/src/programmers/TypedRouteProgrammer.ts +51 -55
  96. package/src/programmers/http/HttpAssertQuerifyProgrammer.ts +58 -59
  97. package/src/programmers/http/HttpIsQuerifyProgrammer.ts +62 -63
  98. package/src/programmers/http/HttpQuerifyProgrammer.ts +96 -105
  99. package/src/programmers/http/HttpValidateQuerifyProgrammer.ts +63 -64
  100. package/src/programmers/internal/CoreMetadataUtil.ts +21 -21
  101. package/src/transform.ts +35 -36
  102. package/src/transformers/FileTransformer.ts +66 -67
  103. package/src/transformers/MethodTransformer.ts +94 -97
  104. package/src/transformers/NodeTransformer.ts +16 -16
  105. package/src/transformers/ParameterDecoratorTransformer.ts +121 -126
  106. package/src/transformers/ParameterTransformer.ts +48 -53
  107. package/src/transformers/TypedExceptionTransformer.ts +49 -51
  108. package/src/transformers/TypedRouteTransformer.ts +95 -96
  109. package/src/typings/Creator.ts +3 -3
  110. package/src/utils/ExceptionManager.ts +112 -112
  111. package/src/utils/Singleton.ts +20 -20
  112. package/src/utils/SourceFinder.ts +57 -60
@@ -1,21 +1,20 @@
1
1
  import { AesPkcs5 } from "@nestia/fetcher/lib/AesPkcs5";
2
2
  import { IEncryptionPassword } from "@nestia/fetcher/lib/IEncryptionPassword";
3
3
  import {
4
- CallHandler,
5
- Delete,
6
- ExecutionContext,
7
- Get,
8
- NestInterceptor,
9
- Patch,
10
- Post,
11
- Put,
12
- UseInterceptors,
13
- applyDecorators,
4
+ CallHandler,
5
+ Delete,
6
+ ExecutionContext,
7
+ Get,
8
+ NestInterceptor,
9
+ Patch,
10
+ Post,
11
+ Put,
12
+ UseInterceptors,
13
+ applyDecorators,
14
14
  } from "@nestjs/common";
15
15
  import { HttpArgumentsHost } from "@nestjs/common/interfaces";
16
16
  import express from "express";
17
17
  import { catchError, map } from "rxjs/operators";
18
-
19
18
  import typia from "typia";
20
19
 
21
20
  import { IResponseBodyStringifier } from "../options/IResponseBodyStringifier";
@@ -47,145 +46,137 @@ import { route_error } from "./internal/route_error";
47
46
  * @author Jeongho Nam - https://github.com/samchon
48
47
  */
49
48
  export namespace EncryptedRoute {
50
- /**
51
- * Encrypted router decorator function for the GET method.
52
- *
53
- * @param paths Path(s) of the HTTP request
54
- * @returns Method decorator
55
- */
56
- export const Get = Generator("Get");
57
-
58
- /**
59
- * Encrypted router decorator function for the GET method.
60
- *
61
- * @param paths Path(s) of the HTTP request
62
- * @returns Method decorator
63
- */
64
- export const Post = Generator("Post");
65
-
66
- /**
67
- * Encrypted router decorator function for the PATCH method.
68
- *
69
- * @param path Path of the HTTP request
70
- * @returns Method decorator
71
- */
72
- export const Patch = Generator("Patch");
73
-
74
- /**
75
- * Encrypted router decorator function for the PUT method.
76
- *
77
- * @param path Path of the HTTP request
78
- * @returns Method decorator
79
- */
80
- export const Put = Generator("Put");
81
-
82
- /**
83
- * Encrypted router decorator function for the DELETE method.
84
- *
85
- * @param path Path of the HTTP request
86
- * @returns Method decorator
87
- */
88
- export const Delete = Generator("Delete");
89
-
90
- function Generator(method: "Get" | "Post" | "Put" | "Patch" | "Delete") {
91
- function route(path?: string | string[]): MethodDecorator;
92
- function route<T>(
93
- stringify?: IResponseBodyStringifier<T> | null,
94
- ): MethodDecorator;
95
- function route<T>(
96
- path: string | string[],
97
- stringify?: IResponseBodyStringifier<T> | null,
98
- ): MethodDecorator;
99
-
100
- function route(...args: any[]): MethodDecorator {
101
- const [path, stringify] = get_path_and_stringify(
102
- `EncryptedRoute.${method}`,
103
- )(...args);
104
- return applyDecorators(
105
- ROUTERS[method](path),
106
- UseInterceptors(
107
- new EncryptedRouteInterceptor(method, stringify),
108
- ),
109
- );
110
- }
111
- return route;
49
+ /**
50
+ * Encrypted router decorator function for the GET method.
51
+ *
52
+ * @param paths Path(s) of the HTTP request
53
+ * @returns Method decorator
54
+ */
55
+ export const Get = Generator("Get");
56
+
57
+ /**
58
+ * Encrypted router decorator function for the GET method.
59
+ *
60
+ * @param paths Path(s) of the HTTP request
61
+ * @returns Method decorator
62
+ */
63
+ export const Post = Generator("Post");
64
+
65
+ /**
66
+ * Encrypted router decorator function for the PATCH method.
67
+ *
68
+ * @param path Path of the HTTP request
69
+ * @returns Method decorator
70
+ */
71
+ export const Patch = Generator("Patch");
72
+
73
+ /**
74
+ * Encrypted router decorator function for the PUT method.
75
+ *
76
+ * @param path Path of the HTTP request
77
+ * @returns Method decorator
78
+ */
79
+ export const Put = Generator("Put");
80
+
81
+ /**
82
+ * Encrypted router decorator function for the DELETE method.
83
+ *
84
+ * @param path Path of the HTTP request
85
+ * @returns Method decorator
86
+ */
87
+ export const Delete = Generator("Delete");
88
+
89
+ function Generator(method: "Get" | "Post" | "Put" | "Patch" | "Delete") {
90
+ function route(path?: string | string[]): MethodDecorator;
91
+ function route<T>(
92
+ stringify?: IResponseBodyStringifier<T> | null,
93
+ ): MethodDecorator;
94
+ function route<T>(
95
+ path: string | string[],
96
+ stringify?: IResponseBodyStringifier<T> | null,
97
+ ): MethodDecorator;
98
+
99
+ function route(...args: any[]): MethodDecorator {
100
+ const [path, stringify] = get_path_and_stringify(
101
+ `EncryptedRoute.${method}`,
102
+ )(...args);
103
+ return applyDecorators(
104
+ ROUTERS[method](path),
105
+ UseInterceptors(new EncryptedRouteInterceptor(method, stringify)),
106
+ );
112
107
  }
108
+ return route;
109
+ }
113
110
  }
114
111
 
115
112
  for (const method of [
116
- typia.json.isStringify,
117
- typia.json.assertStringify,
118
- typia.json.validateStringify,
119
- typia.json.stringify,
113
+ typia.json.isStringify,
114
+ typia.json.assertStringify,
115
+ typia.json.validateStringify,
116
+ typia.json.stringify,
120
117
  ])
121
- for (const [key, value] of Object.entries(method))
122
- for (const deco of [
123
- EncryptedRoute.Get,
124
- EncryptedRoute.Delete,
125
- EncryptedRoute.Post,
126
- EncryptedRoute.Put,
127
- EncryptedRoute.Patch,
128
- ])
129
- (deco as any)[key] = value;
118
+ for (const [key, value] of Object.entries(method))
119
+ for (const deco of [
120
+ EncryptedRoute.Get,
121
+ EncryptedRoute.Delete,
122
+ EncryptedRoute.Post,
123
+ EncryptedRoute.Put,
124
+ EncryptedRoute.Patch,
125
+ ])
126
+ (deco as any)[key] = value;
130
127
 
131
128
  /**
132
129
  * @internal
133
130
  */
134
131
  class EncryptedRouteInterceptor implements NestInterceptor {
135
- public constructor(
136
- private readonly method: string,
137
- private readonly stringify: (input: any) => string,
138
- ) {}
139
-
140
- public intercept(context: ExecutionContext, next: CallHandler) {
141
- const http: HttpArgumentsHost = context.switchToHttp();
142
- return next.handle().pipe(
143
- map((value) => {
144
- const param:
145
- | IEncryptionPassword
146
- | IEncryptionPassword.Closure
147
- | undefined = Reflect.getMetadata(
148
- ENCRYPTION_METADATA_KEY,
149
- context.getClass(),
150
- );
151
- if (!param)
152
- throw NoTransformConfigureError(
153
- `EncryptedRoute.${this.method}`,
154
- );
155
-
156
- const headers: Singleton<Record<string, string>> =
157
- new Singleton(() => {
158
- const request: express.Request = http.getRequest();
159
- return headers_to_object(request.headers);
160
- });
161
- const body: string | undefined = this.stringify(value);
162
- const password: IEncryptionPassword =
163
- typeof param === "function"
164
- ? param({
165
- headers: headers.get(),
166
- body,
167
- direction: "encode",
168
- })
169
- : param;
170
-
171
- const response: express.Response = http.getResponse();
172
- response.header("Content-Type", "text/plain");
173
-
174
- if (body === undefined) return body;
175
- return AesPkcs5.encrypt(body, password.key, password.iv);
176
- }),
177
- catchError((err) => route_error(http.getRequest(), err)),
132
+ public constructor(
133
+ private readonly method: string,
134
+ private readonly stringify: (input: any) => string,
135
+ ) {}
136
+
137
+ public intercept(context: ExecutionContext, next: CallHandler) {
138
+ const http: HttpArgumentsHost = context.switchToHttp();
139
+ return next.handle().pipe(
140
+ map((value) => {
141
+ const param:
142
+ | IEncryptionPassword
143
+ | IEncryptionPassword.Closure
144
+ | undefined = Reflect.getMetadata(
145
+ ENCRYPTION_METADATA_KEY,
146
+ context.getClass(),
178
147
  );
179
- }
148
+ if (!param)
149
+ throw NoTransformConfigureError(`EncryptedRoute.${this.method}`);
150
+
151
+ const headers: Singleton<Record<string, string>> = new Singleton(() => {
152
+ const request: express.Request = http.getRequest();
153
+ return headers_to_object(request.headers);
154
+ });
155
+ const body: string | undefined = this.stringify(value);
156
+ const password: IEncryptionPassword =
157
+ typeof param === "function"
158
+ ? param({
159
+ headers: headers.get(),
160
+ body,
161
+ direction: "encode",
162
+ })
163
+ : param;
164
+
165
+ if (body === undefined) return body;
166
+ return AesPkcs5.encrypt(body, password.key, password.iv);
167
+ }),
168
+ catchError((err) => route_error(http.getRequest(), err)),
169
+ );
170
+ }
180
171
  }
181
172
 
182
173
  /**
183
174
  * @internal
184
175
  */
185
176
  const ROUTERS = {
186
- Get,
187
- Post,
188
- Put,
189
- Patch,
190
- Delete,
177
+ Get,
178
+ Post,
179
+ Put,
180
+ Patch,
181
+ Delete,
191
182
  };
@@ -1,75 +1,72 @@
1
- import {
2
- BadRequestException,
3
- ExecutionContext,
4
- createParamDecorator,
5
- } from "@nestjs/common";
6
- import type express from "express";
7
- import type { FastifyRequest } from "fastify";
8
-
9
- import { assert } from "typia";
10
-
11
- import { get_text_body } from "./internal/get_text_body";
12
- import { validate_request_body } from "./internal/validate_request_body";
13
-
14
- /**
15
- * Plain body decorator.
16
- *
17
- * `PlainBody` is a decorator function getting full body text from the HTTP request.
18
- *
19
- * If you adjust the regular {@link Body} decorator function to the body parameter,
20
- * you can't get the full body text because the {@link Body} tries to convert the
21
- * body text to JSON object. Therefore, `@nestia/core` provides this `PlainBody`
22
- * decorator function to get the full body text.
23
- *
24
- * ```typescript
25
- * \@TypedRoute.Post("memo")
26
- * public store
27
- * (
28
- * \@PlainBody() body: string
29
- * ): void;
30
- * ```
31
- *
32
- * @return Parameter decorator
33
- * @author Jeongho Nam - https://github.com/samchon
34
- */
35
- export function PlainBody(): ParameterDecorator;
36
-
37
- /**
38
- * @internal
39
- */
40
- export function PlainBody(
41
- assert?: (input: unknown) => string,
42
- ): ParameterDecorator {
43
- const checker = assert
44
- ? validate_request_body("PlainBody")({
45
- type: "assert",
46
- assert,
47
- })
48
- : null;
49
- return createParamDecorator(async function PlainBody(
50
- _data: any,
51
- context: ExecutionContext,
52
- ) {
53
- const request: express.Request | FastifyRequest = context
54
- .switchToHttp()
55
- .getRequest();
56
- if (!isTextPlain(request.headers["content-type"]))
57
- throw new BadRequestException(
58
- `Request body type is not "text/plain".`,
59
- );
60
- const value: string = await get_text_body(request);
61
- if (checker) {
62
- const error: Error | null = checker(value);
63
- if (error !== null) throw error;
64
- }
65
- return value;
66
- })();
67
- }
68
- Object.assign(PlainBody, assert);
69
-
70
- const isTextPlain = (text?: string): boolean =>
71
- text !== undefined &&
72
- text
73
- .split(";")
74
- .map((str) => str.trim())
75
- .some((str) => str === "text/plain");
1
+ import {
2
+ BadRequestException,
3
+ ExecutionContext,
4
+ createParamDecorator,
5
+ } from "@nestjs/common";
6
+ import type express from "express";
7
+ import type { FastifyRequest } from "fastify";
8
+ import { assert } from "typia";
9
+
10
+ import { get_text_body } from "./internal/get_text_body";
11
+ import { validate_request_body } from "./internal/validate_request_body";
12
+
13
+ /**
14
+ * Plain body decorator.
15
+ *
16
+ * `PlainBody` is a decorator function getting full body text from the HTTP request.
17
+ *
18
+ * If you adjust the regular {@link Body} decorator function to the body parameter,
19
+ * you can't get the full body text because the {@link Body} tries to convert the
20
+ * body text to JSON object. Therefore, `@nestia/core` provides this `PlainBody`
21
+ * decorator function to get the full body text.
22
+ *
23
+ * ```typescript
24
+ * \@TypedRoute.Post("memo")
25
+ * public store
26
+ * (
27
+ * \@PlainBody() body: string
28
+ * ): void;
29
+ * ```
30
+ *
31
+ * @return Parameter decorator
32
+ * @author Jeongho Nam - https://github.com/samchon
33
+ */
34
+ export function PlainBody(): ParameterDecorator;
35
+
36
+ /**
37
+ * @internal
38
+ */
39
+ export function PlainBody(
40
+ assert?: (input: unknown) => string,
41
+ ): ParameterDecorator {
42
+ const checker = assert
43
+ ? validate_request_body("PlainBody")({
44
+ type: "assert",
45
+ assert,
46
+ })
47
+ : null;
48
+ return createParamDecorator(async function PlainBody(
49
+ _data: any,
50
+ context: ExecutionContext,
51
+ ) {
52
+ const request: express.Request | FastifyRequest = context
53
+ .switchToHttp()
54
+ .getRequest();
55
+ if (!isTextPlain(request.headers["content-type"]))
56
+ throw new BadRequestException(`Request body type is not "text/plain".`);
57
+ const value: string = await get_text_body(request);
58
+ if (checker) {
59
+ const error: Error | null = checker(value);
60
+ if (error !== null) throw error;
61
+ }
62
+ return value;
63
+ })();
64
+ }
65
+ Object.assign(PlainBody, assert);
66
+
67
+ const isTextPlain = (text?: string): boolean =>
68
+ text !== undefined &&
69
+ text
70
+ .split(";")
71
+ .map((str) => str.trim())
72
+ .some((str) => str === "text/plain");
@@ -1,60 +1,59 @@
1
- import {
2
- BadRequestException,
3
- ExecutionContext,
4
- createParamDecorator,
5
- } from "@nestjs/common";
6
- import type express from "express";
7
- import type { FastifyRequest } from "fastify";
8
-
9
- import { assert, is, misc, validate } from "typia";
10
-
11
- import { IRequestBodyValidator } from "../options/IRequestBodyValidator";
12
- import { validate_request_body } from "./internal/validate_request_body";
13
-
14
- /**
15
- * Type safe body decorator.
16
- *
17
- * `TypedBody` is a decorator function getting `application/json` typed data from
18
- * request body. Also, it validates the request body data type through
19
- * [typia](https://github.com/samchon/typia) and the validation speed is
20
- * maximum 20,000x times faster than `class-validator`.
21
- *
22
- * For reference, when the request body data is not following the promised type `T`,
23
- * `BadRequestException` error (status code: 400) would be thrown.
24
- *
25
- * @param validator Custom validator if required. Default is `typia.assert()`
26
- * @author Jeongho Nam - https://github.com/samchon
27
- */
28
- export function TypedBody<T>(
29
- validator?: IRequestBodyValidator<T>,
30
- ): ParameterDecorator {
31
- const checker = validate_request_body("TypedBody")(validator);
32
- return createParamDecorator(function TypedBody(
33
- _unknown: any,
34
- context: ExecutionContext,
35
- ) {
36
- const request: express.Request | FastifyRequest = context
37
- .switchToHttp()
38
- .getRequest();
39
- if (isApplicationJson(request.headers["content-type"]) === false)
40
- throw new BadRequestException(
41
- `Request body type is not "application/json".`,
42
- );
43
-
44
- const error: Error | null = checker(request.body);
45
- if (error !== null) throw error;
46
- return request.body;
47
- })();
48
- }
49
-
50
- Object.assign(TypedBody, misc.clone);
51
- Object.assign(TypedBody, is);
52
- Object.assign(TypedBody, assert);
53
- Object.assign(TypedBody, validate);
54
-
55
- const isApplicationJson = (text?: string): boolean =>
56
- text !== undefined &&
57
- text
58
- .split(";")
59
- .map((str) => str.trim())
60
- .some((str) => str === "application/json");
1
+ import {
2
+ BadRequestException,
3
+ ExecutionContext,
4
+ createParamDecorator,
5
+ } from "@nestjs/common";
6
+ import type express from "express";
7
+ import type { FastifyRequest } from "fastify";
8
+ import { assert, is, misc, validate } from "typia";
9
+
10
+ import { IRequestBodyValidator } from "../options/IRequestBodyValidator";
11
+ import { validate_request_body } from "./internal/validate_request_body";
12
+
13
+ /**
14
+ * Type safe body decorator.
15
+ *
16
+ * `TypedBody` is a decorator function getting `application/json` typed data from
17
+ * request body. Also, it validates the request body data type through
18
+ * [typia](https://github.com/samchon/typia) and the validation speed is
19
+ * maximum 20,000x times faster than `class-validator`.
20
+ *
21
+ * For reference, when the request body data is not following the promised type `T`,
22
+ * `BadRequestException` error (status code: 400) would be thrown.
23
+ *
24
+ * @param validator Custom validator if required. Default is `typia.assert()`
25
+ * @author Jeongho Nam - https://github.com/samchon
26
+ */
27
+ export function TypedBody<T>(
28
+ validator?: IRequestBodyValidator<T>,
29
+ ): ParameterDecorator {
30
+ const checker = validate_request_body("TypedBody")(validator);
31
+ return createParamDecorator(function TypedBody(
32
+ _unknown: any,
33
+ context: ExecutionContext,
34
+ ) {
35
+ const request: express.Request | FastifyRequest = context
36
+ .switchToHttp()
37
+ .getRequest();
38
+ if (isApplicationJson(request.headers["content-type"]) === false)
39
+ throw new BadRequestException(
40
+ `Request body type is not "application/json".`,
41
+ );
42
+
43
+ const error: Error | null = checker(request.body);
44
+ if (error !== null) throw error;
45
+ return request.body;
46
+ })();
47
+ }
48
+
49
+ Object.assign(TypedBody, misc.clone);
50
+ Object.assign(TypedBody, is);
51
+ Object.assign(TypedBody, assert);
52
+ Object.assign(TypedBody, validate);
53
+
54
+ const isApplicationJson = (text?: string): boolean =>
55
+ text !== undefined &&
56
+ text
57
+ .split(";")
58
+ .map((str) => str.trim())
59
+ .some((str) => str === "application/json");