@nestia/core 3.0.0-dev.20231209 → 3.0.0

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 (132) hide show
  1. package/README.md +12 -9
  2. package/lib/decorators/DynamicModule.js +3 -3
  3. package/lib/decorators/DynamicModule.js.map +1 -1
  4. package/lib/decorators/EncryptedBody.js +14 -13
  5. package/lib/decorators/EncryptedBody.js.map +1 -1
  6. package/lib/decorators/EncryptedModule.d.ts +1 -1
  7. package/lib/decorators/EncryptedModule.js +45 -21
  8. package/lib/decorators/EncryptedModule.js.map +1 -1
  9. package/lib/decorators/EncryptedRoute.d.ts +5 -5
  10. package/lib/decorators/EncryptedRoute.js +12 -29
  11. package/lib/decorators/EncryptedRoute.js.map +1 -1
  12. package/lib/decorators/PlainBody.js +3 -0
  13. package/lib/decorators/PlainBody.js.map +1 -1
  14. package/lib/decorators/SwaggerCustomizer.d.ts +79 -0
  15. package/lib/decorators/SwaggerCustomizer.js +32 -0
  16. package/lib/decorators/SwaggerCustomizer.js.map +1 -0
  17. package/lib/decorators/TypedBody.js +3 -0
  18. package/lib/decorators/TypedBody.js.map +1 -1
  19. package/lib/decorators/TypedException.d.ts +0 -1
  20. package/lib/decorators/TypedException.js +0 -1
  21. package/lib/decorators/TypedException.js.map +1 -1
  22. package/lib/decorators/TypedFormData.d.ts +60 -0
  23. package/lib/decorators/TypedFormData.js +403 -0
  24. package/lib/decorators/TypedFormData.js.map +1 -0
  25. package/lib/decorators/TypedQuery.d.ts +11 -6
  26. package/lib/decorators/TypedQuery.js +6 -1
  27. package/lib/decorators/TypedQuery.js.map +1 -1
  28. package/lib/decorators/TypedRoute.d.ts +5 -5
  29. package/lib/decorators/internal/get_path_and_querify.js +3 -0
  30. package/lib/decorators/internal/get_path_and_querify.js.map +1 -1
  31. package/lib/decorators/internal/load_controller.js.map +1 -1
  32. package/lib/decorators/internal/validate_request_body.d.ts +1 -3
  33. package/lib/decorators/internal/validate_request_body.js +15 -0
  34. package/lib/decorators/internal/validate_request_body.js.map +1 -1
  35. package/lib/decorators/internal/validate_request_form_data.js +79 -0
  36. package/lib/decorators/internal/validate_request_form_data.js.map +1 -0
  37. package/lib/decorators/internal/validate_request_headers.d.ts +1 -3
  38. package/lib/decorators/internal/validate_request_headers.js +15 -0
  39. package/lib/decorators/internal/validate_request_headers.js.map +1 -1
  40. package/lib/decorators/internal/validate_request_query.d.ts +1 -3
  41. package/lib/decorators/internal/validate_request_query.js +15 -0
  42. package/lib/decorators/internal/validate_request_query.js.map +1 -1
  43. package/lib/module.d.ts +2 -0
  44. package/lib/module.js +2 -0
  45. package/lib/module.js.map +1 -1
  46. package/lib/options/IRequestFormDataProps.d.ts +23 -0
  47. package/lib/options/IRequestFormDataProps.js +3 -0
  48. package/lib/options/IRequestFormDataProps.js.map +1 -0
  49. package/lib/programmers/PlainBodyProgrammer.js +1 -1
  50. package/lib/programmers/PlainBodyProgrammer.js.map +1 -1
  51. package/lib/programmers/TypedExceptionProgrammer.js +5 -5
  52. package/lib/programmers/TypedExceptionProgrammer.js.map +1 -1
  53. package/lib/programmers/TypedFormDataBodyProgrammer.d.ts +6 -0
  54. package/lib/programmers/TypedFormDataBodyProgrammer.js +84 -0
  55. package/lib/programmers/TypedFormDataBodyProgrammer.js.map +1 -0
  56. package/lib/programmers/http/HttpQuerifyProgrammer.js +2 -2
  57. package/lib/programmers/http/HttpQuerifyProgrammer.js.map +1 -1
  58. package/lib/transformers/NodeTransformer.js.map +1 -1
  59. package/lib/transformers/ParameterDecoratorTransformer.js +7 -1
  60. package/lib/transformers/ParameterDecoratorTransformer.js.map +1 -1
  61. package/lib/transformers/TypedExceptionTransformer.js +1 -1
  62. package/lib/transformers/TypedExceptionTransformer.js.map +1 -1
  63. package/lib/transformers/TypedRouteTransformer.js +1 -1
  64. package/lib/transformers/TypedRouteTransformer.js.map +1 -1
  65. package/package.json +15 -16
  66. package/src/decorators/DynamicModule.ts +39 -39
  67. package/src/decorators/EncryptedBody.ts +105 -107
  68. package/src/decorators/EncryptedController.ts +38 -38
  69. package/src/decorators/EncryptedModule.ts +96 -79
  70. package/src/decorators/EncryptedRoute.ts +182 -206
  71. package/src/decorators/PlainBody.ts +75 -72
  72. package/src/decorators/SwaggerCustomizer.ts +115 -0
  73. package/src/decorators/TypedBody.ts +62 -59
  74. package/src/decorators/TypedException.ts +90 -89
  75. package/src/decorators/TypedFormData.ts +219 -0
  76. package/src/decorators/TypedHeaders.ts +69 -69
  77. package/src/decorators/TypedParam.ts +65 -65
  78. package/src/decorators/TypedQuery.ts +251 -246
  79. package/src/decorators/TypedRoute.ts +144 -144
  80. package/src/decorators/internal/EncryptedConstant.ts +4 -4
  81. package/src/decorators/internal/NoTransformConfigureError.ts +8 -8
  82. package/src/decorators/internal/get_path_and_querify.ts +106 -103
  83. package/src/decorators/internal/get_path_and_stringify.ts +91 -91
  84. package/src/decorators/internal/get_text_body.ts +20 -20
  85. package/src/decorators/internal/headers_to_object.ts +13 -13
  86. package/src/decorators/internal/load_controller.ts +51 -51
  87. package/src/decorators/internal/route_error.ts +45 -45
  88. package/src/decorators/internal/validate_request_body.ts +72 -57
  89. package/src/decorators/internal/validate_request_form_data.ts +75 -0
  90. package/src/decorators/internal/validate_request_headers.ts +83 -68
  91. package/src/decorators/internal/validate_request_query.ts +71 -56
  92. package/src/index.ts +5 -5
  93. package/src/module.ts +16 -14
  94. package/src/options/INestiaTransformOptions.ts +17 -17
  95. package/src/options/INestiaTransformProject.ts +7 -7
  96. package/src/options/IRequestBodyValidator.ts +20 -20
  97. package/src/options/IRequestFormDataProps.ts +27 -0
  98. package/src/options/IRequestHeadersValidator.ts +22 -22
  99. package/src/options/IRequestQueryValidator.ts +20 -20
  100. package/src/options/IResponseBodyQuerifier.ts +25 -25
  101. package/src/options/IResponseBodyStringifier.ts +25 -25
  102. package/src/programmers/PlainBodyProgrammer.ts +52 -52
  103. package/src/programmers/TypedBodyProgrammer.ts +108 -108
  104. package/src/programmers/TypedExceptionProgrammer.ts +71 -72
  105. package/src/programmers/TypedFormDataBodyProgrammer.ts +108 -0
  106. package/src/programmers/TypedHeadersProgrammer.ts +56 -56
  107. package/src/programmers/TypedParamProgrammer.ts +24 -24
  108. package/src/programmers/TypedQueryBodyProgrammer.ts +56 -56
  109. package/src/programmers/TypedQueryProgrammer.ts +56 -56
  110. package/src/programmers/TypedQueryRouteProgrammer.ts +51 -51
  111. package/src/programmers/TypedRouteProgrammer.ts +51 -51
  112. package/src/programmers/http/HttpAssertQuerifyProgrammer.ts +58 -58
  113. package/src/programmers/http/HttpIsQuerifyProgrammer.ts +62 -62
  114. package/src/programmers/http/HttpQuerifyProgrammer.ts +96 -96
  115. package/src/programmers/http/HttpValidateQuerifyProgrammer.ts +63 -63
  116. package/src/programmers/internal/CoreMetadataUtil.ts +21 -21
  117. package/src/transform.ts +35 -35
  118. package/src/transformers/FileTransformer.ts +66 -66
  119. package/src/transformers/MethodTransformer.ts +94 -94
  120. package/src/transformers/NodeTransformer.ts +16 -16
  121. package/src/transformers/ParameterDecoratorTransformer.ts +120 -121
  122. package/src/transformers/ParameterTransformer.ts +48 -48
  123. package/src/transformers/TypedExceptionTransformer.ts +48 -49
  124. package/src/transformers/TypedRouteTransformer.ts +88 -95
  125. package/src/typings/Creator.ts +3 -3
  126. package/src/utils/ExceptionManager.ts +112 -112
  127. package/src/utils/Singleton.ts +20 -20
  128. package/src/utils/SourceFinder.ts +57 -57
  129. package/lib/decorators/internal/get_binary_body.js +0 -66
  130. package/lib/decorators/internal/get_binary_body.js.map +0 -1
  131. package/src/decorators/internal/get_binary_body.ts +0 -18
  132. /package/lib/decorators/internal/{get_binary_body.d.ts → validate_request_form_data.d.ts} +0 -0
@@ -0,0 +1,219 @@
1
+ import type { MultipartFile } from "@fastify/multipart";
2
+ import {
3
+ BadRequestException,
4
+ ExecutionContext,
5
+ InternalServerErrorException,
6
+ createParamDecorator,
7
+ } from "@nestjs/common";
8
+ import type { HttpArgumentsHost } from "@nestjs/common/interfaces";
9
+ import type express from "express";
10
+ import type { FastifyReply, FastifyRequest } from "fastify";
11
+ import multer from "multer";
12
+ import typia from "typia";
13
+
14
+ import type { IRequestFormDataProps } from "../options/IRequestFormDataProps";
15
+ import { Singleton } from "../utils/Singleton";
16
+ import { validate_request_form_data } from "./internal/validate_request_form_data";
17
+
18
+ /**
19
+ * Type safe multipart/form-data decorator.
20
+ *
21
+ * `TypedFormData.Body()` is a request body decorator function for the
22
+ * `multipart/form-data` content type. It automatically casts property type
23
+ * following its DTO definition, and performs the type validation too.
24
+ *
25
+ * Also, `TypedFormData.Body()` is much easier and type safer than `@nest.UploadFile()`.
26
+ * If you're considering the [SDK library](https://nestia.io/docs/sdk/sdk) generation,
27
+ * only `TypedFormData.Body()` can do it. Therefore, I recommend you to use
28
+ * `TypedFormData.Body()` instead of the `@nest.UploadFile()` function.
29
+ *
30
+ * For reference, target type `T` must follow such restriction. Of course, if actual
31
+ * form-data values are different with their promised type `T`,
32
+ * `BadRequestException` error (status code: 400) would be thrown.
33
+ *
34
+ * 1. Type `T` must be an object type
35
+ * 2. Do not allow dynamic property
36
+ * 3. Only `boolean`, `bigint`, `number`, `string`, `Blob`, `File` or their array types are allowed
37
+ * 4. By the way, union type never be not allowed
38
+ *
39
+ * By the way, if you're using `fastify`, you have to setup `@fastify/multipart`
40
+ * and configure like below when composing the NestJS application. If you don't do
41
+ * that, `@TypedFormData.Body()` will not work properly, and throw 500 internal
42
+ * server error when `Blob` or `File` type being utilized.
43
+ *
44
+ * ```typescript
45
+ * import multipart from "fastify-multipart";
46
+ * import { NestFactory } from "@nestjs/core";
47
+ * import {
48
+ * FastifyAdapter,
49
+ * NestFastifyApplication
50
+ * } from "@nestjs/platform-fastify";
51
+ *
52
+ * export async function main() {
53
+ * const app = await NestFactory.create<NestFastifyApplication>(
54
+ * AppModule,
55
+ * new FastifyAdapter(),
56
+ * );
57
+ * app.register(multipart);
58
+ * await app.listen(3000);
59
+ * }
60
+ * ```
61
+ *
62
+ * @todo Change to ReadableStream through configuring storage engine of multer
63
+ * @author Jeongho Nam - https://github.com/samchon
64
+ */
65
+ export namespace TypedFormData {
66
+ /**
67
+ * Request body decorator.
68
+ *
69
+ * Request body decorator for the `multipart/form-data` type.
70
+ *
71
+ * Much easier and type safer than `@nest.UploadFile()` decorator.
72
+ *
73
+ * @param props Automatically filled by transformer
74
+ */
75
+ export function Body<T extends object>(
76
+ props?: IRequestFormDataProps<T>,
77
+ ): ParameterDecorator {
78
+ const checker = validate_request_form_data(props);
79
+ const predicator = (type: "express" | "fastify") =>
80
+ new Singleton(() =>
81
+ type === "express" ? decodeExpress(props!) : decodeFastify(props!),
82
+ );
83
+ return createParamDecorator(async function TypedFormDataBody(
84
+ _unknown: any,
85
+ context: ExecutionContext,
86
+ ) {
87
+ const http: HttpArgumentsHost = context.switchToHttp();
88
+ const request: express.Request = http.getRequest();
89
+ if (isMultipartFormData(request.headers["content-type"]) === false)
90
+ throw new BadRequestException(
91
+ `Request body type is not "multipart/form-data".`,
92
+ );
93
+
94
+ const decoder = isExpressRequest(request)
95
+ ? predicator("express").get()
96
+ : predicator("fastify").get();
97
+ const data: FormData = await decoder({
98
+ request: request as any,
99
+ response: http.getResponse(),
100
+ });
101
+ const output: T | Error = checker(data);
102
+ if (output instanceof Error) throw output;
103
+ return output;
104
+ })();
105
+ }
106
+ Object.assign(Body, typia.http.assertFormData);
107
+ Object.assign(Body, typia.http.isFormData);
108
+ Object.assign(Body, typia.http.validateFormData);
109
+ }
110
+
111
+ /**
112
+ * @internal
113
+ */
114
+ const decodeExpress = <T>(props: IRequestFormDataProps<T>) => {
115
+ const upload = multerApplication.get().fields(
116
+ props!.files.map((file) => ({
117
+ name: file.name,
118
+ ...(file.limit === 1 ? { maxCount: 1 } : {}),
119
+ })),
120
+ );
121
+ const interceptor = (request: express.Request, response: express.Response) =>
122
+ new Promise<void>((resolve, reject) =>
123
+ upload(request, response, (error) => {
124
+ if (error) reject(error);
125
+ else resolve();
126
+ }),
127
+ );
128
+ return async (socket: {
129
+ request: express.Request;
130
+ response: express.Response;
131
+ }): Promise<FormData> => {
132
+ await interceptor(socket.request, socket.response);
133
+
134
+ const data: FormData = new FormData();
135
+ for (const [key, value] of Object.entries(socket.request.body))
136
+ for (const elem of String(value).split(",")) data.append(key, elem);
137
+
138
+ if (socket.request.files) parseFiles(data)(socket.request.files);
139
+ return data;
140
+ };
141
+ };
142
+
143
+ /**
144
+ * @internal
145
+ */
146
+ const decodeFastify =
147
+ <T>(_props: IRequestFormDataProps<T>) =>
148
+ async (socket: {
149
+ request: FastifyRequest & {
150
+ files?(): AsyncIterableIterator<MultipartFile>;
151
+ };
152
+ response: FastifyReply;
153
+ }): Promise<FormData> => {
154
+ if (
155
+ socket.request.files === undefined ||
156
+ typeof socket.request.files !== "function"
157
+ )
158
+ throw new InternalServerErrorException(
159
+ "Have not configured the `fastify-multipart` plugin yet. Inquiry to the backend developer.",
160
+ );
161
+ const data: FormData = new FormData();
162
+ for (const [key, value] of Object.entries(socket.request.body ?? {}))
163
+ for (const elem of String(value).split(",")) data.append(key, elem);
164
+ for await (const file of socket.request.files())
165
+ data.append(
166
+ file.fieldname,
167
+ new File([await file.toBuffer()], file.filename, {
168
+ type: file.mimetype,
169
+ }),
170
+ );
171
+ return data;
172
+ };
173
+
174
+ /**
175
+ * @internal
176
+ */
177
+ const parseFiles =
178
+ (data: FormData) =>
179
+ (files: Express.Multer.File[] | Record<string, Express.Multer.File[]>) => {
180
+ if (Array.isArray(files))
181
+ for (const file of files)
182
+ data.append(
183
+ file.fieldname,
184
+ new File([file.buffer], file.originalname, {
185
+ type: file.mimetype,
186
+ }),
187
+ );
188
+ else
189
+ for (const [key, value] of Object.entries(files))
190
+ for (const file of value)
191
+ data.append(
192
+ key,
193
+ new File([file.buffer], file.originalname, {
194
+ type: file.mimetype,
195
+ }),
196
+ );
197
+ };
198
+
199
+ /**
200
+ * @internal
201
+ */
202
+ const isMultipartFormData = (text?: string): boolean =>
203
+ text !== undefined &&
204
+ text
205
+ .split(";")
206
+ .map((str) => str.trim())
207
+ .some((str) => str === "multipart/form-data");
208
+
209
+ /**
210
+ * @internal
211
+ */
212
+ const isExpressRequest = (
213
+ request: express.Request | FastifyRequest,
214
+ ): request is express.Request => (request as express.Request).app !== undefined;
215
+
216
+ /**
217
+ * @internal
218
+ */
219
+ const multerApplication = new Singleton(() => multer());
@@ -1,69 +1,69 @@
1
- import { ExecutionContext, createParamDecorator } from "@nestjs/common";
2
- import type express from "express";
3
- import type { FastifyRequest } from "fastify";
4
- import typia from "typia";
5
-
6
- import { IRequestHeadersValidator } from "../options/IRequestHeadersValidator";
7
- import { validate_request_headers } from "./internal/validate_request_headers";
8
-
9
- /**
10
- * Type safe HTTP headers decorator.
11
- *
12
- * `TypedHeaders` is a decorator function that can parse HTTP headers. It is almost
13
- * same with {@link nest.Headers}, but it can automatically cast property type following
14
- * its DTO definition. Also, `TypedHeaders` performs type validation.
15
- *
16
- * For reference, target type `T` must follow such restrictions. Also, if actual HTTP
17
- * header values are different with their promised type `T`, `BadRequestException`
18
- * error (status code: 400) would be thrown.
19
- *
20
- * 1. Type `T` must be an object type
21
- * 2. Do not allow dynamic property
22
- * 3. Property key must be lower case
23
- * 4. Property value cannot be `null`, but `undefined` is possible
24
- * 5. Only `boolean`, `bigint`, `number`, `string` or their array types are allowed
25
- * 6. By the way, union type never be not allowed
26
- * 7. Property `set-cookie` must be array type
27
- * 8. Those properties cannot be array type
28
- * - age
29
- * - authorization
30
- * - content-length
31
- * - content-type
32
- * - etag
33
- * - expires
34
- * - from
35
- * - host
36
- * - if-modified-since
37
- * - if-unmodified-since
38
- * - last-modified
39
- * - location
40
- * - max-forwards
41
- * - proxy-authorization
42
- * - referer
43
- * - retry-after
44
- * - server
45
- * - user-agent
46
- *
47
- * @returns Parameter decorator
48
- * @author Jeongho Nam - https://github.com/samchon
49
- */
50
- export function TypedHeaders<T extends object>(
51
- validator?: IRequestHeadersValidator<T>,
52
- ): ParameterDecorator {
53
- const checker = validate_request_headers(validator);
54
- return createParamDecorator(function TypedHeaders(
55
- _unknown: any,
56
- context: ExecutionContext,
57
- ) {
58
- const request: express.Request | FastifyRequest = context
59
- .switchToHttp()
60
- .getRequest();
61
-
62
- const output: T | Error = checker(request.headers);
63
- if (output instanceof Error) throw output;
64
- return output;
65
- })();
66
- }
67
- Object.assign(TypedHeaders, typia.http.assertHeaders);
68
- Object.assign(TypedHeaders, typia.http.isHeaders);
69
- Object.assign(TypedHeaders, typia.http.validateHeaders);
1
+ import { ExecutionContext, createParamDecorator } from "@nestjs/common";
2
+ import type express from "express";
3
+ import type { FastifyRequest } from "fastify";
4
+ import typia from "typia";
5
+
6
+ import { IRequestHeadersValidator } from "../options/IRequestHeadersValidator";
7
+ import { validate_request_headers } from "./internal/validate_request_headers";
8
+
9
+ /**
10
+ * Type safe HTTP headers decorator.
11
+ *
12
+ * `TypedHeaders` is a decorator function that can parse HTTP headers. It is almost
13
+ * same with {@link nest.Headers}, but it can automatically cast property type following
14
+ * its DTO definition. Also, `TypedHeaders` performs type validation.
15
+ *
16
+ * For reference, target type `T` must follow such restrictions. Also, if actual HTTP
17
+ * header values are different with their promised type `T`, `BadRequestException`
18
+ * error (status code: 400) would be thrown.
19
+ *
20
+ * 1. Type `T` must be an object type
21
+ * 2. Do not allow dynamic property
22
+ * 3. Property key must be lower case
23
+ * 4. Property value cannot be `null`, but `undefined` is possible
24
+ * 5. Only `boolean`, `bigint`, `number`, `string` or their array types are allowed
25
+ * 6. By the way, union type never be not allowed
26
+ * 7. Property `set-cookie` must be array type
27
+ * 8. Those properties cannot be array type
28
+ * - age
29
+ * - authorization
30
+ * - content-length
31
+ * - content-type
32
+ * - etag
33
+ * - expires
34
+ * - from
35
+ * - host
36
+ * - if-modified-since
37
+ * - if-unmodified-since
38
+ * - last-modified
39
+ * - location
40
+ * - max-forwards
41
+ * - proxy-authorization
42
+ * - referer
43
+ * - retry-after
44
+ * - server
45
+ * - user-agent
46
+ *
47
+ * @returns Parameter decorator
48
+ * @author Jeongho Nam - https://github.com/samchon
49
+ */
50
+ export function TypedHeaders<T extends object>(
51
+ validator?: IRequestHeadersValidator<T>,
52
+ ): ParameterDecorator {
53
+ const checker = validate_request_headers(validator);
54
+ return createParamDecorator(function TypedHeaders(
55
+ _unknown: any,
56
+ context: ExecutionContext,
57
+ ) {
58
+ const request: express.Request | FastifyRequest = context
59
+ .switchToHttp()
60
+ .getRequest();
61
+
62
+ const output: T | Error = checker(request.headers);
63
+ if (output instanceof Error) throw output;
64
+ return output;
65
+ })();
66
+ }
67
+ Object.assign(TypedHeaders, typia.http.assertHeaders);
68
+ Object.assign(TypedHeaders, typia.http.isHeaders);
69
+ Object.assign(TypedHeaders, typia.http.validateHeaders);
@@ -1,65 +1,65 @@
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 typia, { TypeGuardError } from "typia";
9
-
10
- import { NoTransformConfigureError } from "./internal/NoTransformConfigureError";
11
-
12
- /**
13
- * Type safe URL parameter decorator.
14
- *
15
- * `TypedParam` is a decorator function getting specific typed parameter from the
16
- * HTTP request URL. It's almost same with the {@link nest.Param}, but `TypedParam`
17
- * automatically casts parameter value to be following its type, and validates it.
18
- *
19
- * ```typescript
20
- * import { tags } from "typia";
21
- *
22
- * \@TypedRoute.Get("shopping/sales/:id/:no/:paused")
23
- * public async pause
24
- * (
25
- * \@TypedParam("id", "uuid"), id: string & tags.Format<"uuid">,
26
- * \@TypedParam("no") id: number & tags.Type<"uint32">
27
- * \@TypedParam("paused") paused: boolean | null
28
- * ): Promise<void>;
29
- * ```
30
- *
31
- * @param name URL Parameter name
32
- * @returns Parameter decorator
33
- *
34
- * @author Jeongho Nam - https://github.com/samchon
35
- */
36
- export function TypedParam<T extends boolean | bigint | number | string | null>(
37
- name: string,
38
- assert?: (value: string) => T,
39
- ): ParameterDecorator {
40
- if (assert === undefined) throw NoTransformConfigureError("TypedParam");
41
-
42
- return createParamDecorator(function TypedParam(
43
- {}: any,
44
- context: ExecutionContext,
45
- ) {
46
- const request: express.Request | FastifyRequest = context
47
- .switchToHttp()
48
- .getRequest();
49
- const str: string = (request.params as any)[name];
50
- try {
51
- return assert(str);
52
- } catch (exp) {
53
- if (typia.is<TypeGuardError>(exp))
54
- throw new BadRequestException({
55
- path: exp.path,
56
- reason: exp.message,
57
- expected: exp.expected,
58
- value: exp.value,
59
- message: `Invalid URL parameter value on "${name}".`,
60
- });
61
- throw exp;
62
- }
63
- })(name);
64
- }
65
- Object.assign(TypedParam, typia.http.parameter);
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 typia, { TypeGuardError } from "typia";
9
+
10
+ import { NoTransformConfigureError } from "./internal/NoTransformConfigureError";
11
+
12
+ /**
13
+ * Type safe URL parameter decorator.
14
+ *
15
+ * `TypedParam` is a decorator function getting specific typed parameter from the
16
+ * HTTP request URL. It's almost same with the {@link nest.Param}, but `TypedParam`
17
+ * automatically casts parameter value to be following its type, and validates it.
18
+ *
19
+ * ```typescript
20
+ * import { tags } from "typia";
21
+ *
22
+ * \@TypedRoute.Get("shopping/sales/:id/:no/:paused")
23
+ * public async pause
24
+ * (
25
+ * \@TypedParam("id", "uuid"), id: string & tags.Format<"uuid">,
26
+ * \@TypedParam("no") id: number & tags.Type<"uint32">
27
+ * \@TypedParam("paused") paused: boolean | null
28
+ * ): Promise<void>;
29
+ * ```
30
+ *
31
+ * @param name URL Parameter name
32
+ * @returns Parameter decorator
33
+ *
34
+ * @author Jeongho Nam - https://github.com/samchon
35
+ */
36
+ export function TypedParam<T extends boolean | bigint | number | string | null>(
37
+ name: string,
38
+ assert?: (value: string) => T,
39
+ ): ParameterDecorator {
40
+ if (assert === undefined) throw NoTransformConfigureError("TypedParam");
41
+
42
+ return createParamDecorator(function TypedParam(
43
+ {}: any,
44
+ context: ExecutionContext,
45
+ ) {
46
+ const request: express.Request | FastifyRequest = context
47
+ .switchToHttp()
48
+ .getRequest();
49
+ const str: string = (request.params as any)[name];
50
+ try {
51
+ return assert(str);
52
+ } catch (exp) {
53
+ if (typia.is<TypeGuardError>(exp))
54
+ throw new BadRequestException({
55
+ path: exp.path,
56
+ reason: exp.message,
57
+ expected: exp.expected,
58
+ value: exp.value,
59
+ message: `Invalid URL parameter value on "${name}".`,
60
+ });
61
+ throw exp;
62
+ }
63
+ })(name);
64
+ }
65
+ Object.assign(TypedParam, typia.http.parameter);