@nestia/core 12.0.0-dev.20260601.1 → 12.0.0-dev.20260612.2

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 (116) hide show
  1. package/LICENSE +21 -21
  2. package/MIGRATION.md +169 -169
  3. package/README.md +93 -93
  4. package/lib/adaptors/McpAdaptor.d.ts +75 -0
  5. package/lib/adaptors/McpAdaptor.js +257 -0
  6. package/lib/adaptors/McpAdaptor.js.map +1 -0
  7. package/lib/adaptors/WebSocketAdaptor.js +4 -4
  8. package/lib/adaptors/WebSocketAdaptor.js.map +1 -1
  9. package/lib/decorators/McpRoute.d.ts +69 -0
  10. package/lib/decorators/McpRoute.js +58 -0
  11. package/lib/decorators/McpRoute.js.map +1 -0
  12. package/lib/decorators/TypedParam.js +4 -4
  13. package/lib/decorators/TypedParam.js.map +1 -1
  14. package/lib/decorators/TypedRoute.js +1 -1
  15. package/lib/decorators/TypedRoute.js.map +1 -1
  16. package/lib/decorators/internal/IMcpRouteReflect.d.ts +2 -0
  17. package/lib/decorators/internal/IMcpRouteReflect.js +3 -0
  18. package/lib/decorators/internal/IMcpRouteReflect.js.map +1 -0
  19. package/lib/decorators/internal/get_path_and_querify.js +4 -4
  20. package/lib/decorators/internal/get_path_and_querify.js.map +1 -1
  21. package/lib/decorators/internal/get_path_and_stringify.js +4 -4
  22. package/lib/decorators/internal/get_path_and_stringify.js.map +1 -1
  23. package/lib/decorators/internal/load_controller.js +34 -65
  24. package/lib/decorators/internal/load_controller.js.map +1 -1
  25. package/lib/decorators/internal/validate_request_body.js +4 -4
  26. package/lib/decorators/internal/validate_request_body.js.map +1 -1
  27. package/lib/decorators/internal/validate_request_form_data.js +4 -4
  28. package/lib/decorators/internal/validate_request_form_data.js.map +1 -1
  29. package/lib/decorators/internal/validate_request_headers.js +4 -4
  30. package/lib/decorators/internal/validate_request_headers.js.map +1 -1
  31. package/lib/decorators/internal/validate_request_query.js +4 -4
  32. package/lib/decorators/internal/validate_request_query.js.map +1 -1
  33. package/lib/module.d.ts +2 -0
  34. package/lib/module.js +2 -0
  35. package/lib/module.js.map +1 -1
  36. package/native/cmd/ttsc-nestia/main.go +11 -11
  37. package/native/go.mod +32 -32
  38. package/native/go.sum +54 -54
  39. package/native/plugin/plan.go +102 -102
  40. package/native/transform/ast.go +32 -32
  41. package/native/transform/build.go +380 -444
  42. package/native/transform/cleanup.go +408 -408
  43. package/native/transform/contributor.go +97 -68
  44. package/native/transform/core_querify.go +231 -227
  45. package/native/transform/core_transform.go +1996 -1713
  46. package/native/transform/core_websocket.go +115 -115
  47. package/native/transform/exports.go +13 -13
  48. package/native/transform/mcp_transform.go +414 -0
  49. package/native/transform/node_transform.go +357 -0
  50. package/native/transform/path_rewrite.go +285 -285
  51. package/native/transform/printer.go +244 -244
  52. package/native/transform/rewrite.go +668 -662
  53. package/native/transform/run.go +73 -73
  54. package/native/transform/transform.go +336 -403
  55. package/native/transform/typia_fast.go +352 -326
  56. package/native/transform/typia_replacement.go +24 -24
  57. package/native/transform.cjs +43 -43
  58. package/package.json +15 -8
  59. package/src/adaptors/McpAdaptor.ts +276 -0
  60. package/src/adaptors/WebSocketAdaptor.ts +429 -429
  61. package/src/decorators/DynamicModule.ts +44 -44
  62. package/src/decorators/EncryptedBody.ts +97 -97
  63. package/src/decorators/EncryptedController.ts +40 -40
  64. package/src/decorators/EncryptedModule.ts +98 -98
  65. package/src/decorators/EncryptedRoute.ts +213 -213
  66. package/src/decorators/HumanRoute.ts +21 -21
  67. package/src/decorators/McpRoute.ts +154 -0
  68. package/src/decorators/NoTransformConfigurationError.ts +40 -40
  69. package/src/decorators/PlainBody.ts +76 -76
  70. package/src/decorators/SwaggerCustomizer.ts +97 -97
  71. package/src/decorators/SwaggerExample.ts +180 -180
  72. package/src/decorators/TypedBody.ts +57 -57
  73. package/src/decorators/TypedException.ts +147 -147
  74. package/src/decorators/TypedFormData.ts +187 -187
  75. package/src/decorators/TypedHeaders.ts +66 -66
  76. package/src/decorators/TypedParam.ts +77 -77
  77. package/src/decorators/TypedQuery.ts +234 -234
  78. package/src/decorators/TypedRoute.ts +198 -196
  79. package/src/decorators/WebSocketRoute.ts +242 -242
  80. package/src/decorators/doNotThrowTransformError.ts +5 -5
  81. package/src/decorators/internal/EncryptedConstant.ts +2 -2
  82. package/src/decorators/internal/IMcpRouteReflect.ts +40 -0
  83. package/src/decorators/internal/IWebSocketRouteReflect.ts +23 -23
  84. package/src/decorators/internal/get_path_and_querify.ts +94 -94
  85. package/src/decorators/internal/get_path_and_stringify.ts +110 -110
  86. package/src/decorators/internal/get_text_body.ts +16 -16
  87. package/src/decorators/internal/headers_to_object.ts +11 -11
  88. package/src/decorators/internal/is_request_body_undefined.ts +12 -12
  89. package/src/decorators/internal/load_controller.ts +91 -76
  90. package/src/decorators/internal/route_error.ts +43 -43
  91. package/src/decorators/internal/validate_request_body.ts +64 -64
  92. package/src/decorators/internal/validate_request_form_data.ts +67 -67
  93. package/src/decorators/internal/validate_request_headers.ts +76 -76
  94. package/src/decorators/internal/validate_request_query.ts +83 -83
  95. package/src/index.ts +5 -5
  96. package/src/module.ts +25 -23
  97. package/src/options/IRequestBodyValidator.ts +20 -20
  98. package/src/options/IRequestFormDataProps.ts +27 -27
  99. package/src/options/IRequestHeadersValidator.ts +22 -22
  100. package/src/options/IRequestQueryValidator.ts +20 -20
  101. package/src/options/IResponseBodyQuerifier.ts +25 -25
  102. package/src/options/IResponseBodyStringifier.ts +30 -30
  103. package/src/transform.ts +101 -101
  104. package/src/typings/Creator.ts +3 -3
  105. package/src/typings/get-function-location.d.ts +7 -7
  106. package/src/utils/ArrayUtil.ts +7 -7
  107. package/src/utils/ExceptionManager.ts +115 -115
  108. package/src/utils/Singleton.ts +16 -16
  109. package/src/utils/SourceFinder.ts +54 -54
  110. package/src/utils/VersioningStrategy.ts +27 -27
  111. package/native/transform/cleanup_test.go +0 -76
  112. package/native/transform/commonjs_import_alias_test.go +0 -49
  113. package/native/transform/core_dispatch_test.go +0 -127
  114. package/native/transform/path_rewrite_test.go +0 -243
  115. package/native/transform/rewrite_test.go +0 -118
  116. package/native/transform/rewrite_unique_base_test.go +0 -48
@@ -1,147 +1,147 @@
1
- /**
2
- * > You must configure the generic argument `T`
3
- *
4
- * Exception decorator.
5
- *
6
- * `TypedException` is a decorator function describing HTTP exception and its
7
- * type which could be occurred in the method.
8
- *
9
- * For reference, this decorator function does not affect to the method's
10
- * behavior, but only affects to the swagger documents generation. Also, it does
11
- * not affect to the SDK library generation yet, but will be used in the
12
- * future.
13
- *
14
- * @author Jeongho Nam - https://github.com/samchon
15
- * @param props Properties for the exception
16
- * @returns Method decorator
17
- */
18
- export function TypedException(props: TypedException.IProps<unknown>): never;
19
-
20
- /**
21
- * > You must configure the generic argument `T`
22
- *
23
- * Exception decorator.
24
- *
25
- * `TypedException` is a decorator function describing HTTP exception and its
26
- * type which could be occurred in the method.
27
- *
28
- * For reference, this decorator function does not affect to the method's
29
- * behavior, but only affects to the swagger documents generation. Also, it does
30
- * not affect to the SDK library generation yet, but will be used in the
31
- * future.
32
- *
33
- * @author Jeongho Nam - https://github.com/samchon
34
- * @deprecated Use {@link TypedException.IProps} typed function instead. This
35
- * typed function is deprecated and will be removed in the next major update.
36
- * @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
37
- * @param description Description about the exception
38
- * @returns Method decorator
39
- */
40
- export function TypedException(
41
- status: number | "2XX" | "3XX" | "4XX" | "5XX",
42
- description?: string | undefined,
43
- ): never;
44
-
45
- /**
46
- * Exception decorator.
47
- *
48
- * `TypedException` is a decorator function describing HTTP exception and its
49
- * type which could be occurred in the method.
50
- *
51
- * For reference, this decorator function does not affect to the method's
52
- * behavior, but only affects to the swagger documents generation. Also, it does
53
- * not affect to the SDK library generation yet, but will be used in the
54
- * future.
55
- *
56
- * @author Jeongho Nam - https://github.com/samchon
57
- * @template T Type of the exception
58
- * @param props Properties for the exception
59
- * @returns Method decorator
60
- */
61
- export function TypedException<T>(
62
- props: TypedException.IProps<T>,
63
- ): MethodDecorator;
64
-
65
- /**
66
- * Exception decorator.
67
- *
68
- * `TypedException` is a decorator function describing HTTP exception and its
69
- * type which could be occurred in the method.
70
- *
71
- * For reference, this decorator function does not affect to the method's
72
- * behavior, but only affects to the swagger documents generation. Also, it does
73
- * not affect to the SDK library generation yet, but will be used in the
74
- * future.
75
- *
76
- * @author Jeongho Nam - https://github.com/samchon
77
- * @deprecated Use {@link TypedException.IProps} typed function instead. This
78
- * typed function is deprecated and will be removed in the next major update.
79
- * @template T Type of the exception
80
- * @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
81
- * @param description Description about the exception
82
- * @returns Method decorator
83
- */
84
- export function TypedException<T>(
85
- status: number | "2XX" | "3XX" | "4XX" | "5XX",
86
- description?: string | undefined,
87
- ): MethodDecorator;
88
-
89
- /** @internal */
90
- export function TypedException<T>(...args: any[]): MethodDecorator {
91
- const props: TypedException.IProps<T> =
92
- typeof args[0] === "object"
93
- ? args[0]
94
- : { status: args[0], description: args[1] };
95
- return function TypedException(
96
- target: Object | T,
97
- propertyKey: string | symbol,
98
- descriptor: TypedPropertyDescriptor<any>,
99
- ) {
100
- const array: TypedException.IProps<any>[] = (() => {
101
- const oldbie: TypedException.IProps<any>[] | undefined =
102
- Reflect.getMetadata(
103
- "nestia/TypedException",
104
- (target as any)[propertyKey],
105
- );
106
- if (oldbie !== undefined) return oldbie;
107
-
108
- const newbie: TypedException.IProps<any>[] = [];
109
- Reflect.defineMetadata(
110
- "nestia/TypedException",
111
- newbie,
112
- (target as any)[propertyKey],
113
- );
114
- return newbie;
115
- })();
116
- array.push(props);
117
- return descriptor;
118
- };
119
- }
120
- export namespace TypedException {
121
- /** Properties for the exception. */
122
- export interface IProps<T> {
123
- /** Status number or pattern like "2XX", "3XX", "4XX", "5XX". */
124
- status: number | "2XX" | "3XX" | "4XX" | "5XX";
125
-
126
- /** Description about the exception. */
127
- description?: string | undefined;
128
-
129
- /** Example value. */
130
- example?: T | undefined;
131
-
132
- /** Collection of examples for the exception. */
133
- examples?: Record<string, IExample<T>> | undefined;
134
- }
135
-
136
- /** Metadata collected in the {@link IProps.examples}. */
137
- export interface IExample<T> {
138
- /** Summary of the example. */
139
- summary?: string | undefined;
140
-
141
- /** Description of the example. */
142
- description?: string | undefined;
143
-
144
- /** Value of the example. */
145
- value: T;
146
- }
147
- }
1
+ /**
2
+ * > You must configure the generic argument `T`
3
+ *
4
+ * Exception decorator.
5
+ *
6
+ * `TypedException` is a decorator function describing HTTP exception and its
7
+ * type which could be occurred in the method.
8
+ *
9
+ * For reference, this decorator function does not affect to the method's
10
+ * behavior, but only affects to the swagger documents generation. Also, it does
11
+ * not affect to the SDK library generation yet, but will be used in the
12
+ * future.
13
+ *
14
+ * @author Jeongho Nam - https://github.com/samchon
15
+ * @param props Properties for the exception
16
+ * @returns Method decorator
17
+ */
18
+ export function TypedException(props: TypedException.IProps<unknown>): never;
19
+
20
+ /**
21
+ * > You must configure the generic argument `T`
22
+ *
23
+ * Exception decorator.
24
+ *
25
+ * `TypedException` is a decorator function describing HTTP exception and its
26
+ * type which could be occurred in the method.
27
+ *
28
+ * For reference, this decorator function does not affect to the method's
29
+ * behavior, but only affects to the swagger documents generation. Also, it does
30
+ * not affect to the SDK library generation yet, but will be used in the
31
+ * future.
32
+ *
33
+ * @author Jeongho Nam - https://github.com/samchon
34
+ * @deprecated Use {@link TypedException.IProps} typed function instead. This
35
+ * typed function is deprecated and will be removed in the next major update.
36
+ * @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
37
+ * @param description Description about the exception
38
+ * @returns Method decorator
39
+ */
40
+ export function TypedException(
41
+ status: number | "2XX" | "3XX" | "4XX" | "5XX",
42
+ description?: string | undefined,
43
+ ): never;
44
+
45
+ /**
46
+ * Exception decorator.
47
+ *
48
+ * `TypedException` is a decorator function describing HTTP exception and its
49
+ * type which could be occurred in the method.
50
+ *
51
+ * For reference, this decorator function does not affect to the method's
52
+ * behavior, but only affects to the swagger documents generation. Also, it does
53
+ * not affect to the SDK library generation yet, but will be used in the
54
+ * future.
55
+ *
56
+ * @author Jeongho Nam - https://github.com/samchon
57
+ * @template T Type of the exception
58
+ * @param props Properties for the exception
59
+ * @returns Method decorator
60
+ */
61
+ export function TypedException<T>(
62
+ props: TypedException.IProps<T>,
63
+ ): MethodDecorator;
64
+
65
+ /**
66
+ * Exception decorator.
67
+ *
68
+ * `TypedException` is a decorator function describing HTTP exception and its
69
+ * type which could be occurred in the method.
70
+ *
71
+ * For reference, this decorator function does not affect to the method's
72
+ * behavior, but only affects to the swagger documents generation. Also, it does
73
+ * not affect to the SDK library generation yet, but will be used in the
74
+ * future.
75
+ *
76
+ * @author Jeongho Nam - https://github.com/samchon
77
+ * @deprecated Use {@link TypedException.IProps} typed function instead. This
78
+ * typed function is deprecated and will be removed in the next major update.
79
+ * @template T Type of the exception
80
+ * @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
81
+ * @param description Description about the exception
82
+ * @returns Method decorator
83
+ */
84
+ export function TypedException<T>(
85
+ status: number | "2XX" | "3XX" | "4XX" | "5XX",
86
+ description?: string | undefined,
87
+ ): MethodDecorator;
88
+
89
+ /** @internal */
90
+ export function TypedException<T>(...args: any[]): MethodDecorator {
91
+ const props: TypedException.IProps<T> =
92
+ typeof args[0] === "object"
93
+ ? args[0]
94
+ : { status: args[0], description: args[1] };
95
+ return function TypedException(
96
+ target: Object | T,
97
+ propertyKey: string | symbol,
98
+ descriptor: TypedPropertyDescriptor<any>,
99
+ ) {
100
+ const array: TypedException.IProps<any>[] = (() => {
101
+ const oldbie: TypedException.IProps<any>[] | undefined =
102
+ Reflect.getMetadata(
103
+ "nestia/TypedException",
104
+ (target as any)[propertyKey],
105
+ );
106
+ if (oldbie !== undefined) return oldbie;
107
+
108
+ const newbie: TypedException.IProps<any>[] = [];
109
+ Reflect.defineMetadata(
110
+ "nestia/TypedException",
111
+ newbie,
112
+ (target as any)[propertyKey],
113
+ );
114
+ return newbie;
115
+ })();
116
+ array.push(props);
117
+ return descriptor;
118
+ };
119
+ }
120
+ export namespace TypedException {
121
+ /** Properties for the exception. */
122
+ export interface IProps<T> {
123
+ /** Status number or pattern like "2XX", "3XX", "4XX", "5XX". */
124
+ status: number | "2XX" | "3XX" | "4XX" | "5XX";
125
+
126
+ /** Description about the exception. */
127
+ description?: string | undefined;
128
+
129
+ /** Example value. */
130
+ example?: T | undefined;
131
+
132
+ /** Collection of examples for the exception. */
133
+ examples?: Record<string, IExample<T>> | undefined;
134
+ }
135
+
136
+ /** Metadata collected in the {@link IProps.examples}. */
137
+ export interface IExample<T> {
138
+ /** Summary of the example. */
139
+ summary?: string | undefined;
140
+
141
+ /** Description of the example. */
142
+ description?: string | undefined;
143
+
144
+ /** Value of the example. */
145
+ value: T;
146
+ }
147
+ }
@@ -1,187 +1,187 @@
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
22
- * `@nest.UploadFile()`. If you're considering the [SDK
23
- * library](https://nestia.io/docs/sdk/sdk) generation, only
24
- * `TypedFormData.Body()` can do it. Therefore, I recommend you to use
25
- * `TypedFormData.Body()` instead of the `@nest.UploadFile()` function.
26
- *
27
- * For reference, target type `T` must follow such restriction. Of course, if
28
- * actual form-data values are different with their promised type `T`,
29
- * `BadRequestException` error (status code: 400) would be thrown.
30
- *
31
- * 1. Type `T` must be an object type
32
- * 2. Do not allow dynamic property
33
- * 3. Only `boolean`, `bigint`, `number`, `string`, `Blob`, `File` or their array
34
- * types are allowed
35
- * 4. By the way, union type never be not allowed
36
- *
37
- * By the way, if you're using `fastify`, you have to setup `fastify-multer` and
38
- * configure like below when composing the NestJS application. If you don't do
39
- * that, `@TypedFormData.Body()` will not work properly, and throw 500 internal
40
- * server error when `Blob` or `File` type being utilized.
41
- *
42
- * ```typescript
43
- * import { NestFactory } from "@nestjs/core";
44
- * import {
45
- * FastifyAdapter,
46
- * NestFastifyApplication,
47
- * } from "@nestjs/platform-fastify";
48
- * import fastifyMulter from "fastify-multer";
49
- *
50
- * export async function main() {
51
- * const app = await NestFactory.create<NestFastifyApplication>(
52
- * AppModule,
53
- * new FastifyAdapter(),
54
- * );
55
- * app.register(fastifyMulter.contentParser);
56
- * await app.listen(3000);
57
- * }
58
- * ```
59
- *
60
- * @author Jeongho Nam - https://github.com/samchon
61
- * @todo Change to ReadableStream through configuring storage engine of multer
62
- */
63
- export namespace TypedFormData {
64
- /**
65
- * Request body decorator.
66
- *
67
- * Request body decorator for the `multipart/form-data` type.
68
- *
69
- * Much easier and type safer than `@nest.UploadFile()` decorator.
70
- *
71
- * @param factory Factory function ncreating the `multer` or `fastify-multer`
72
- * instance. In the factory function, you also can specify the multer
73
- * composition options like `storage` engine.
74
- */
75
- export function Body<Multer extends IMulterBase>(
76
- factory: () => Multer | Promise<Multer>,
77
- ): ParameterDecorator;
78
-
79
- /** @internal */
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
- /** Base type of the `multer` or `fastify-multer`. */
115
- export interface IMulterBase {
116
- single(fieldName: string): any;
117
- array(fieldName: string, maxCount?: number): any;
118
- fields(fields: readonly object[]): any;
119
- any(): any;
120
- none(): any;
121
- }
122
- }
123
-
124
- /** @internal */
125
- const decode = <T>(
126
- multer: ExpressMulter.Multer,
127
- props: IRequestFormDataProps<T>,
128
- ) => {
129
- const upload = multer.fields(
130
- props!.files.map((file) => ({
131
- name: file.name,
132
- ...(file.limit === 1 ? { maxCount: 1 } : {}),
133
- })),
134
- );
135
- const interceptor = (request: express.Request, response: express.Response) =>
136
- new Promise<void>((resolve, reject) =>
137
- upload(request, response, (error) => {
138
- if (error) reject(error);
139
- else resolve();
140
- }),
141
- );
142
- return async (socket: {
143
- request: express.Request;
144
- response: express.Response;
145
- }): Promise<FormData> => {
146
- await interceptor(socket.request, socket.response);
147
-
148
- const data: FormData = new FormData();
149
- for (const [key, value] of Object.entries(socket.request.body))
150
- if (Array.isArray(value))
151
- for (const elem of value) data.append(key, String(elem));
152
- else data.append(key, String(value));
153
- if (socket.request.files) parseFiles(data)(socket.request.files);
154
- return data;
155
- };
156
- };
157
-
158
- /** @internal */
159
- const parseFiles =
160
- (data: FormData) =>
161
- (files: Express.Multer.File[] | Record<string, Express.Multer.File[]>) => {
162
- if (Array.isArray(files))
163
- for (const file of files)
164
- data.append(
165
- file.fieldname,
166
- new File([file.buffer as any], file.originalname, {
167
- type: file.mimetype,
168
- }),
169
- );
170
- else
171
- for (const [key, value] of Object.entries(files))
172
- for (const file of value)
173
- data.append(
174
- key,
175
- new File([file.buffer as any], file.originalname, {
176
- type: file.mimetype,
177
- }),
178
- );
179
- };
180
-
181
- /** @internal */
182
- const isMultipartFormData = (text?: string): boolean =>
183
- text !== undefined &&
184
- text
185
- .split(";")
186
- .map((str) => str.trim())
187
- .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
22
+ * `@nest.UploadFile()`. If you're considering the [SDK
23
+ * library](https://nestia.io/docs/sdk/sdk) generation, only
24
+ * `TypedFormData.Body()` can do it. Therefore, I recommend you to use
25
+ * `TypedFormData.Body()` instead of the `@nest.UploadFile()` function.
26
+ *
27
+ * For reference, target type `T` must follow such restriction. Of course, if
28
+ * actual form-data values are different with their promised type `T`,
29
+ * `BadRequestException` error (status code: 400) would be thrown.
30
+ *
31
+ * 1. Type `T` must be an object type
32
+ * 2. Do not allow dynamic property
33
+ * 3. Only `boolean`, `bigint`, `number`, `string`, `Blob`, `File` or their array
34
+ * types are allowed
35
+ * 4. By the way, union type never be not allowed
36
+ *
37
+ * By the way, if you're using `fastify`, you have to setup `fastify-multer` and
38
+ * configure like below when composing the NestJS application. If you don't do
39
+ * that, `@TypedFormData.Body()` will not work properly, and throw 500 internal
40
+ * server error when `Blob` or `File` type being utilized.
41
+ *
42
+ * ```typescript
43
+ * import { NestFactory } from "@nestjs/core";
44
+ * import {
45
+ * FastifyAdapter,
46
+ * NestFastifyApplication,
47
+ * } from "@nestjs/platform-fastify";
48
+ * import fastifyMulter from "fastify-multer";
49
+ *
50
+ * export async function main() {
51
+ * const app = await NestFactory.create<NestFastifyApplication>(
52
+ * AppModule,
53
+ * new FastifyAdapter(),
54
+ * );
55
+ * app.register(fastifyMulter.contentParser);
56
+ * await app.listen(3000);
57
+ * }
58
+ * ```
59
+ *
60
+ * @author Jeongho Nam - https://github.com/samchon
61
+ * @todo Change to ReadableStream through configuring storage engine of multer
62
+ */
63
+ export namespace TypedFormData {
64
+ /**
65
+ * Request body decorator.
66
+ *
67
+ * Request body decorator for the `multipart/form-data` type.
68
+ *
69
+ * Much easier and type safer than `@nest.UploadFile()` decorator.
70
+ *
71
+ * @param factory Factory function ncreating the `multer` or `fastify-multer`
72
+ * instance. In the factory function, you also can specify the multer
73
+ * composition options like `storage` engine.
74
+ */
75
+ export function Body<Multer extends IMulterBase>(
76
+ factory: () => Multer | Promise<Multer>,
77
+ ): ParameterDecorator;
78
+
79
+ /** @internal */
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
+ /** Base type of the `multer` or `fastify-multer`. */
115
+ export interface IMulterBase {
116
+ single(fieldName: string): any;
117
+ array(fieldName: string, maxCount?: number): any;
118
+ fields(fields: readonly object[]): any;
119
+ any(): any;
120
+ none(): any;
121
+ }
122
+ }
123
+
124
+ /** @internal */
125
+ const decode = <T>(
126
+ multer: ExpressMulter.Multer,
127
+ props: IRequestFormDataProps<T>,
128
+ ) => {
129
+ const upload = multer.fields(
130
+ props!.files.map((file) => ({
131
+ name: file.name,
132
+ ...(file.limit === 1 ? { maxCount: 1 } : {}),
133
+ })),
134
+ );
135
+ const interceptor = (request: express.Request, response: express.Response) =>
136
+ new Promise<void>((resolve, reject) =>
137
+ upload(request, response, (error) => {
138
+ if (error) reject(error);
139
+ else resolve();
140
+ }),
141
+ );
142
+ return async (socket: {
143
+ request: express.Request;
144
+ response: express.Response;
145
+ }): Promise<FormData> => {
146
+ await interceptor(socket.request, socket.response);
147
+
148
+ const data: FormData = new FormData();
149
+ for (const [key, value] of Object.entries(socket.request.body))
150
+ if (Array.isArray(value))
151
+ for (const elem of value) data.append(key, String(elem));
152
+ else data.append(key, String(value));
153
+ if (socket.request.files) parseFiles(data)(socket.request.files);
154
+ return data;
155
+ };
156
+ };
157
+
158
+ /** @internal */
159
+ const parseFiles =
160
+ (data: FormData) =>
161
+ (files: Express.Multer.File[] | Record<string, Express.Multer.File[]>) => {
162
+ if (Array.isArray(files))
163
+ for (const file of files)
164
+ data.append(
165
+ file.fieldname,
166
+ new File([file.buffer as any], file.originalname, {
167
+ type: file.mimetype,
168
+ }),
169
+ );
170
+ else
171
+ for (const [key, value] of Object.entries(files))
172
+ for (const file of value)
173
+ data.append(
174
+ key,
175
+ new File([file.buffer as any], file.originalname, {
176
+ type: file.mimetype,
177
+ }),
178
+ );
179
+ };
180
+
181
+ /** @internal */
182
+ const isMultipartFormData = (text?: string): boolean =>
183
+ text !== undefined &&
184
+ text
185
+ .split(";")
186
+ .map((str) => str.trim())
187
+ .some((str) => str === "multipart/form-data");