@nestia/core 2.6.3-dev.20240328 → 2.6.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 (32) hide show
  1. package/package.json +3 -3
  2. package/src/decorators/EncryptedBody.ts +105 -105
  3. package/src/decorators/EncryptedModule.ts +96 -96
  4. package/src/decorators/PlainBody.ts +75 -75
  5. package/src/decorators/SwaggerCustomizer.ts +116 -116
  6. package/src/decorators/TypedBody.ts +62 -62
  7. package/src/decorators/TypedException.ts +90 -90
  8. package/src/decorators/TypedFormData.ts +219 -219
  9. package/src/decorators/TypedQuery.ts +251 -251
  10. package/src/decorators/TypedRoute.ts +144 -144
  11. package/src/decorators/internal/get_path_and_querify.ts +106 -106
  12. package/src/decorators/internal/load_controller.ts +51 -51
  13. package/src/decorators/internal/validate_request_body.ts +72 -72
  14. package/src/decorators/internal/validate_request_form_data.ts +75 -75
  15. package/src/decorators/internal/validate_request_headers.ts +83 -83
  16. package/src/decorators/internal/validate_request_query.ts +71 -71
  17. package/src/module.ts +16 -16
  18. package/src/options/IRequestFormDataProps.ts +27 -27
  19. package/src/programmers/PlainBodyProgrammer.ts +52 -52
  20. package/src/programmers/TypedExceptionProgrammer.ts +71 -71
  21. package/src/programmers/TypedFormDataBodyProgrammer.ts +108 -108
  22. package/src/programmers/http/HttpQuerifyProgrammer.ts +96 -96
  23. package/src/structures/ISwagger.ts +91 -91
  24. package/src/structures/ISwaggerComponents.ts +29 -29
  25. package/src/structures/ISwaggerInfo.ts +80 -80
  26. package/src/structures/ISwaggerRoute.ts +50 -50
  27. package/src/structures/ISwaggerSecurityScheme.ts +65 -65
  28. package/src/transformers/NodeTransformer.ts +16 -16
  29. package/src/transformers/ParameterDecoratorTransformer.ts +120 -120
  30. package/src/transformers/TypedExceptionTransformer.ts +48 -48
  31. package/src/transformers/TypedRouteTransformer.ts +88 -88
  32. package/src/utils/Singleton.ts +20 -20
@@ -1,219 +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
+ 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());