@nestia/core 3.1.0-dev.20240429 → 3.1.0-dev.20240430-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.
- package/lib/transformers/WebSocketRouteTransformer.js +3 -4
- package/lib/transformers/WebSocketRouteTransformer.js.map +1 -1
- package/package.json +3 -3
- package/src/decorators/DynamicModule.ts +39 -39
- package/src/decorators/EncryptedBody.ts +105 -105
- package/src/decorators/EncryptedController.ts +38 -38
- package/src/decorators/EncryptedModule.ts +96 -96
- package/src/decorators/EncryptedRoute.ts +182 -182
- package/src/decorators/PlainBody.ts +75 -75
- package/src/decorators/TypedBody.ts +62 -62
- package/src/decorators/TypedException.ts +90 -90
- package/src/decorators/TypedFormData.ts +219 -219
- package/src/decorators/TypedHeaders.ts +69 -69
- package/src/decorators/TypedParam.ts +64 -64
- package/src/decorators/TypedRoute.ts +144 -144
- package/src/decorators/internal/EncryptedConstant.ts +4 -4
- package/src/decorators/internal/NoTransformConfigureError.ts +8 -8
- package/src/decorators/internal/get_path_and_querify.ts +106 -106
- package/src/decorators/internal/get_path_and_stringify.ts +91 -91
- package/src/decorators/internal/get_text_body.ts +20 -20
- package/src/decorators/internal/headers_to_object.ts +13 -13
- package/src/decorators/internal/load_controller.ts +51 -51
- package/src/decorators/internal/route_error.ts +45 -45
- package/src/index.ts +5 -5
- package/src/options/INestiaTransformOptions.ts +17 -17
- package/src/options/INestiaTransformProject.ts +7 -7
- package/src/options/IRequestBodyValidator.ts +20 -20
- package/src/options/IRequestFormDataProps.ts +27 -27
- package/src/options/IRequestHeadersValidator.ts +22 -22
- package/src/options/IRequestQueryValidator.ts +20 -20
- package/src/options/IResponseBodyQuerifier.ts +25 -25
- package/src/options/IResponseBodyStringifier.ts +25 -25
- package/src/programmers/PlainBodyProgrammer.ts +52 -52
- package/src/programmers/TypedBodyProgrammer.ts +108 -108
- package/src/programmers/TypedExceptionProgrammer.ts +71 -71
- package/src/programmers/TypedHeadersProgrammer.ts +56 -56
- package/src/programmers/TypedParamProgrammer.ts +24 -24
- package/src/programmers/TypedQueryBodyProgrammer.ts +56 -56
- package/src/programmers/TypedQueryProgrammer.ts +56 -56
- package/src/programmers/TypedQueryRouteProgrammer.ts +51 -51
- package/src/programmers/TypedRouteProgrammer.ts +51 -51
- package/src/programmers/http/HttpAssertQuerifyProgrammer.ts +58 -58
- package/src/programmers/http/HttpIsQuerifyProgrammer.ts +62 -62
- package/src/programmers/http/HttpValidateQuerifyProgrammer.ts +63 -63
- package/src/programmers/internal/CoreMetadataUtil.ts +21 -21
- package/src/transform.ts +35 -35
- package/src/transformers/FileTransformer.ts +66 -66
- package/src/transformers/MethodTransformer.ts +97 -97
- package/src/transformers/NodeTransformer.ts +16 -16
- package/src/transformers/ParameterTransformer.ts +48 -48
- package/src/transformers/TypedExceptionTransformer.ts +44 -44
- package/src/transformers/TypedRouteTransformer.ts +81 -81
- package/src/transformers/WebSocketRouteTransformer.ts +8 -3
- package/src/typings/Creator.ts +3 -3
- package/src/utils/ExceptionManager.ts +112 -112
- package/src/utils/Singleton.ts +20 -20
- package/src/utils/SourceFinder.ts +57 -57
|
@@ -1,90 +1,90 @@
|
|
|
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 type
|
|
7
|
-
* which could be occured in the method.
|
|
8
|
-
*
|
|
9
|
-
* For reference, this decorator function does not affect to the method's behavior,
|
|
10
|
-
* but only affects to the swagger documents generation. Also, it does not affect to
|
|
11
|
-
* the SDK library generation yet, but will be used in the future.
|
|
12
|
-
*
|
|
13
|
-
* @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
|
|
14
|
-
* @param description Description about the exception
|
|
15
|
-
* @returns Method decorator
|
|
16
|
-
*
|
|
17
|
-
* @author Jeongho Nam - https://github.com/samchon
|
|
18
|
-
*/
|
|
19
|
-
export function TypedException(
|
|
20
|
-
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
21
|
-
description?: string | undefined,
|
|
22
|
-
): never;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Exception decorator.
|
|
26
|
-
*
|
|
27
|
-
* `TypedException` is a decorator function describing HTTP exception and its type
|
|
28
|
-
* which could be occured in the method.
|
|
29
|
-
*
|
|
30
|
-
* For reference, this decorator function does not affect to the method's behavior,
|
|
31
|
-
* but only affects to the swagger documents generation. Also, it does not affect to
|
|
32
|
-
* the SDK library generation yet, but will be used in the future.
|
|
33
|
-
*
|
|
34
|
-
* @template T Type of the exception
|
|
35
|
-
* @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
|
|
36
|
-
* @param description Description about the exception
|
|
37
|
-
* @returns Method decorator
|
|
38
|
-
*
|
|
39
|
-
* @author Jeongho Nam - https://github.com/samchon
|
|
40
|
-
*/
|
|
41
|
-
export function TypedException<T>(
|
|
42
|
-
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
43
|
-
description?: string | undefined,
|
|
44
|
-
): MethodDecorator;
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @internal
|
|
48
|
-
*/
|
|
49
|
-
export function TypedException<T>(
|
|
50
|
-
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
51
|
-
description?: string | undefined,
|
|
52
|
-
type?: string | undefined,
|
|
53
|
-
): MethodDecorator {
|
|
54
|
-
return function TypedException(
|
|
55
|
-
target: Object | T,
|
|
56
|
-
propertyKey: string | symbol,
|
|
57
|
-
descriptor: TypedPropertyDescriptor<any>,
|
|
58
|
-
) {
|
|
59
|
-
const array: IProps[] = (() => {
|
|
60
|
-
const oldbie: IProps[] | undefined = Reflect.getMetadata(
|
|
61
|
-
"nestia/TypedException",
|
|
62
|
-
(target as any)[propertyKey],
|
|
63
|
-
);
|
|
64
|
-
if (oldbie !== undefined) return oldbie;
|
|
65
|
-
|
|
66
|
-
const newbie: IProps[] = [];
|
|
67
|
-
Reflect.defineMetadata(
|
|
68
|
-
"nestia/TypedException",
|
|
69
|
-
newbie,
|
|
70
|
-
(target as any)[propertyKey],
|
|
71
|
-
);
|
|
72
|
-
return newbie;
|
|
73
|
-
})();
|
|
74
|
-
array.push({
|
|
75
|
-
status,
|
|
76
|
-
description,
|
|
77
|
-
type: type!,
|
|
78
|
-
});
|
|
79
|
-
return descriptor;
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* @internal
|
|
85
|
-
*/
|
|
86
|
-
interface IProps {
|
|
87
|
-
status: number | "2XX" | "3XX" | "4XX" | "5XX";
|
|
88
|
-
description?: string | undefined;
|
|
89
|
-
type: string;
|
|
90
|
-
}
|
|
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 type
|
|
7
|
+
* which could be occured in the method.
|
|
8
|
+
*
|
|
9
|
+
* For reference, this decorator function does not affect to the method's behavior,
|
|
10
|
+
* but only affects to the swagger documents generation. Also, it does not affect to
|
|
11
|
+
* the SDK library generation yet, but will be used in the future.
|
|
12
|
+
*
|
|
13
|
+
* @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
|
|
14
|
+
* @param description Description about the exception
|
|
15
|
+
* @returns Method decorator
|
|
16
|
+
*
|
|
17
|
+
* @author Jeongho Nam - https://github.com/samchon
|
|
18
|
+
*/
|
|
19
|
+
export function TypedException(
|
|
20
|
+
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
21
|
+
description?: string | undefined,
|
|
22
|
+
): never;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Exception decorator.
|
|
26
|
+
*
|
|
27
|
+
* `TypedException` is a decorator function describing HTTP exception and its type
|
|
28
|
+
* which could be occured in the method.
|
|
29
|
+
*
|
|
30
|
+
* For reference, this decorator function does not affect to the method's behavior,
|
|
31
|
+
* but only affects to the swagger documents generation. Also, it does not affect to
|
|
32
|
+
* the SDK library generation yet, but will be used in the future.
|
|
33
|
+
*
|
|
34
|
+
* @template T Type of the exception
|
|
35
|
+
* @param status Status number or pattern like "2XX", "3XX", "4XX", "5XX"
|
|
36
|
+
* @param description Description about the exception
|
|
37
|
+
* @returns Method decorator
|
|
38
|
+
*
|
|
39
|
+
* @author Jeongho Nam - https://github.com/samchon
|
|
40
|
+
*/
|
|
41
|
+
export function TypedException<T>(
|
|
42
|
+
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
43
|
+
description?: string | undefined,
|
|
44
|
+
): MethodDecorator;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
export function TypedException<T>(
|
|
50
|
+
status: number | "2XX" | "3XX" | "4XX" | "5XX",
|
|
51
|
+
description?: string | undefined,
|
|
52
|
+
type?: string | undefined,
|
|
53
|
+
): MethodDecorator {
|
|
54
|
+
return function TypedException(
|
|
55
|
+
target: Object | T,
|
|
56
|
+
propertyKey: string | symbol,
|
|
57
|
+
descriptor: TypedPropertyDescriptor<any>,
|
|
58
|
+
) {
|
|
59
|
+
const array: IProps[] = (() => {
|
|
60
|
+
const oldbie: IProps[] | undefined = Reflect.getMetadata(
|
|
61
|
+
"nestia/TypedException",
|
|
62
|
+
(target as any)[propertyKey],
|
|
63
|
+
);
|
|
64
|
+
if (oldbie !== undefined) return oldbie;
|
|
65
|
+
|
|
66
|
+
const newbie: IProps[] = [];
|
|
67
|
+
Reflect.defineMetadata(
|
|
68
|
+
"nestia/TypedException",
|
|
69
|
+
newbie,
|
|
70
|
+
(target as any)[propertyKey],
|
|
71
|
+
);
|
|
72
|
+
return newbie;
|
|
73
|
+
})();
|
|
74
|
+
array.push({
|
|
75
|
+
status,
|
|
76
|
+
description,
|
|
77
|
+
type: type!,
|
|
78
|
+
});
|
|
79
|
+
return descriptor;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @internal
|
|
85
|
+
*/
|
|
86
|
+
interface IProps {
|
|
87
|
+
status: number | "2XX" | "3XX" | "4XX" | "5XX";
|
|
88
|
+
description?: string | undefined;
|
|
89
|
+
type: string;
|
|
90
|
+
}
|
|
@@ -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());
|