refactor: upload image controller

This commit is contained in:
Hackntosh 2024-01-30 21:20:46 +00:00
parent c1528f02c3
commit 34944d9000
3 changed files with 35 additions and 24 deletions

View file

@ -0,0 +1,14 @@
const UploadImageSchema = {
required: true,
schema: {
type: "object",
properties: {
image: {
type: "string",
format: "binary",
},
},
},
};
export default UploadImageSchema;

View file

@ -2,12 +2,9 @@ import {
Body, Body,
Controller, Controller,
Delete, Delete,
FileTypeValidator,
Get, Get,
HttpCode, HttpCode,
MaxFileSizeValidator,
Param, Param,
ParseFilePipe,
Patch, Patch,
Post, Post,
Request, Request,
@ -34,6 +31,8 @@ import { UpdateEmailDTO } from "./dto/update-email.dto";
import { UpdatePasswordDTO } from "./dto/update-password.dto"; import { UpdatePasswordDTO } from "./dto/update-password.dto";
import { File, FileInterceptor } from "@nest-lab/fastify-multer"; import { File, FileInterceptor } from "@nest-lab/fastify-multer";
import { BufferValidator } from "src/validators/buffer-validator.pipe"; import { BufferValidator } from "src/validators/buffer-validator.pipe";
import UploadImageSchema from "./schemas/upload-image.schema";
import UploadImageValidator from "src/validators/upload-image.validator";
@ApiTags("Users") @ApiTags("Users")
@Controller("users") @Controller("users")
@ -110,29 +109,10 @@ export class UserController {
@ApiBearerAuth("JWT") @ApiBearerAuth("JWT")
@UseInterceptors(FileInterceptor("image")) @UseInterceptors(FileInterceptor("image"))
@ApiConsumes("multipart/form-data") @ApiConsumes("multipart/form-data")
@ApiBody({ @ApiBody(UploadImageSchema)
required: true,
schema: {
type: "object",
properties: {
image: {
type: "string",
format: "binary",
},
},
},
})
uploadProfileImage( uploadProfileImage(
@UploadedFile( @UploadedFile(
new ParseFilePipe({ UploadImageValidator,
validators: [
new MaxFileSizeValidator({
maxSize: 15 * 1024 * 1024,
message: "File too big. Max 1MB.",
}),
new FileTypeValidator({ fileType: /^image\/(jpeg|png|webp)$/ }), // File extension validation
],
}),
new BufferValidator(), // Magic number validation new BufferValidator(), // Magic number validation
) )
image: File, image: File,

View file

@ -0,0 +1,17 @@
import {
FileTypeValidator,
MaxFileSizeValidator,
ParseFilePipe,
} from "@nestjs/common";
const UploadImageValidator = new ParseFilePipe({
validators: [
new MaxFileSizeValidator({
maxSize: 15 * 1024 * 1024,
message: "File too big. Max 1MB.",
}),
new FileTypeValidator({ fileType: /^image\/(jpeg|png|webp)$/ }), // File extension validation
],
});
export default UploadImageValidator;