Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add multer support for fastify #941

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@
"typia": ">=6.3.1 <7.0.0"
},
"devDependencies": {
"@fastify/multipart": "^8.1.0",
"@nestjs/common": "^10.3.3",
"@nestjs/core": "^10.3.3",
"@types/express": "^4.17.15",
Expand All @@ -76,6 +75,7 @@
"comment-json": "^4.2.3",
"eslint-plugin-deprecation": "^1.4.1",
"fastify": "^4.25.2",
"fastify-multer": "^2.0.3",
"git-last-commit": "^1.0.1",
"inquirer": "^8.2.5",
"rimraf": "^3.0.2",
Expand Down
65 changes: 35 additions & 30 deletions packages/core/src/decorators/TypedFormData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { Multipart } from "@fastify/multipart";
import {
BadRequestException,
ExecutionContext,
Expand All @@ -8,7 +7,10 @@ import {
import type { HttpArgumentsHost } from "@nestjs/common/interfaces";
import type express from "express";
import type { FastifyReply, FastifyRequest } from "fastify";
import multer from "multer";
import fastifyMulter from "fastify-multer";
import type * as FastifyMulter from "fastify-multer/lib/interfaces";
import "fastify-multer/typings/fastify/index.d.ts";
import expressMulter from "multer";
import typia from "typia";

import type { IRequestFormDataProps } from "../options/IRequestFormDataProps";
Expand Down Expand Up @@ -36,13 +38,13 @@ import { validate_request_form_data } from "./internal/validate_request_form_dat
* 3. Only `boolean`, `bigint`, `number`, `string`, `Blob`, `File` or their array types are allowed
* 4. By the way, union type never be not allowed
*
* By the way, if you're using `fastify`, you have to setup `@fastify/multipart`
* By the way, if you're using `fastify`, you have to setup `fastify-multer`
* and configure like below when composing the NestJS application. If you don't do
* that, `@TypedFormData.Body()` will not work properly, and throw 500 internal
* server error when `Blob` or `File` type being utilized.
*
* ```typescript
* import multipart from "fastify-multipart";
* import fastifyMulter from "fastify-multer";
* import { NestFactory } from "@nestjs/core";
* import {
* FastifyAdapter,
Expand All @@ -54,7 +56,7 @@ import { validate_request_form_data } from "./internal/validate_request_form_dat
* AppModule,
* new FastifyAdapter(),
* );
* app.register(multipart);
* app.register(fastifyMulter.contentParser);
* await app.listen(3000);
* }
* ```
Expand Down Expand Up @@ -112,7 +114,7 @@ export namespace TypedFormData {
* @internal
*/
const decodeExpress = <T>(props: IRequestFormDataProps<T>) => {
const upload = multerApplication.get().fields(
const upload = expressMulter(props.options as expressMulter.Options).fields(
props!.files.map((file) => ({
name: file.name,
...(file.limit === 1 ? { maxCount: 1 } : {}),
Expand Down Expand Up @@ -144,36 +146,44 @@ const decodeExpress = <T>(props: IRequestFormDataProps<T>) => {
/**
* @internal
*/
const decodeFastify =
<T>(_props: IRequestFormDataProps<T>) =>
async (socket: {
request: FastifyRequest & {
parts?(): AsyncIterableIterator<Multipart>;
};
const decodeFastify = <T>(props: IRequestFormDataProps<T>) => {
const fastifyInstance = fastifyMulter(props.options as FastifyMulter.Options);
const upload = fastifyInstance.fields(
props!.files.map((file) => ({
name: file.name,
...(file.limit === 1 ? { maxCount: 1 } : {}),
})),
);
const interceptor = (request: FastifyRequest, response: FastifyReply) =>
new Promise<void>((resolve, reject) =>
upload.call(request.server, request, response, (error) => {
if (error) reject(error);
else resolve();
}),
);
return async (socket: {
request: FastifyRequest;
response: FastifyReply;
}): Promise<FormData> => {
if (
socket.request.files === undefined ||
typeof socket.request.files !== "function"
)
throw new InternalServerErrorException(
"Have not configured the `fastify-multipart` plugin yet. Inquiry to the backend developer.",
"Have not configured the `fastify-multer` plugin yet. Inquiry to the backend developer.",
);

await interceptor(socket.request, socket.response);

const data: FormData = new FormData();
for await (const part of socket.request.parts())
if (part.type === "file")
data.append(
part.fieldname,
new File([await part.toBuffer()], part.filename, {
type: part.mimetype,
}),
);
else if (Array.isArray(part.value))
for (const elem of part.value)
data.append(part.fieldname, String(elem));
else data.append(part.fieldname, String(part.value));
for (const [key, value] of Object.entries(socket.request.body as any))
if (Array.isArray(value))
for (const elem of value) data.append(key, String(elem));
else data.append(key, String(value));
if (socket.request.files) parseFiles(data)(socket.request.files);
return data;
};
};

/**
* @internal
Expand Down Expand Up @@ -216,8 +226,3 @@ const isMultipartFormData = (text?: string): boolean =>
const isExpressRequest = (
request: express.Request | FastifyRequest,
): request is express.Request => (request as express.Request).app !== undefined;

/**
* @internal
*/
const multerApplication = new Singleton(() => multer());
3 changes: 3 additions & 0 deletions packages/core/src/options/IRequestFormDataProps.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type fastifyMulter from "fastify-multer/lib/interfaces";
import type expressMulter from "multer";
import { IValidation } from "typia";

export interface IRequestFormDataProps<T> {
Expand All @@ -6,6 +8,7 @@ export interface IRequestFormDataProps<T> {
| IRequestFormDataProps.IAssert<T>
| IRequestFormDataProps.IIs<T>
| IRequestFormDataProps.IValidate<T>;
options?: expressMulter.Options | fastifyMulter.Options;
}
export namespace IRequestFormDataProps {
export interface IAssert<T> {
Expand Down
4 changes: 2 additions & 2 deletions test/features/multipart-form-data-fastify/src/Backend.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import multipart from "@fastify/multipart";
import core from "@nestia/core";
import { INestApplication } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import {
FastifyAdapter,
NestFastifyApplication,
} from "@nestjs/platform-fastify";
import fastifyMulter from "fastify-multer";
import { Singleton } from "tstl";

export class Backend {
Expand All @@ -19,7 +19,7 @@ export class Backend {
new FastifyAdapter(),
{ logger: false },
);
await app.register(multipart);
await app.register(fastifyMulter.contentParser);
return app;
});

Expand Down
4 changes: 2 additions & 2 deletions test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
},
"homepage": "https://nestia.io",
"devDependencies": {
"@nestia/sdk": "^3.4.0",
"@nestia/sdk": "^3.4.0",
"@nestjs/swagger": "^7.1.2",
"@samchon/openapi": "^0.2.2",
"@types/express": "^4.17.17",
Expand All @@ -39,14 +39,14 @@
"typescript-transform-paths": "^3.4.6"
},
"dependencies": {
"@fastify/multipart": "^8.1.0",
"@nestia/core": "^3.4.0",
"@nestia/e2e": "^0.3.6",
"@nestia/fetcher": "^3.4.0",
"@nestjs/common": "^10.3.5",
"@nestjs/core": "^10.3.5",
"@nestjs/platform-express": "^10.3.5",
"@nestjs/platform-fastify": "^10.3.5",
"fastify-multer": "^2.0.3",
"tgrid": "^1.0.2",
"tstl": "^3.0.0",
"typia": "^6.3.1",
Expand Down
Loading