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