dmitriy-nz / nestjs-form-data

NestJS middleware for handling multipart/form-data, which is primarily used for uploading files.
https://www.npmjs.com/package/nestjs-form-data
MIT License
117 stars 23 forks source link

Does not throwing any error if other fields are invalid #33

Closed dutchman1990 closed 1 year ago

dutchman1990 commented 1 year ago

Issue: Not showing any bad request error if fields are invalid @latest version.

Expexted: Throw error with 400 http error code.

Sample code:

@FormDataRequest({storage: FileSystemStoredFile}) async createStore( @Body(new ValidationPipe({ transform: true })) body: createStoreDTO, @Request() req, @Res() response: Response ) { response.status(200).send(body); }

if I remove @FormDataRequest({storage: FileSystemStoredFile}) from code base it does thorw error as expected for otherfields.

Suggestion: Please update the doc how to store the file after validation passes.

dmitriy-nz commented 1 year ago

@dutchman1990 Hi, provide your createStoreDTO and package.json or nestjs version

dmitriy-nz commented 1 year ago

I reproduced your script and everything works fine. My DTO:

import { IsFile, MemoryStoredFile, MinFileSize } from "nestjs-form-data";
import { IsString, MinLength } from "class-validator";

export class UploadSingleFileDto {

    @IsFile()
    @MinFileSize(3)
    file: MemoryStoredFile;

    @IsString()
    @MinLength(10)
    name: string;

}

Controller method: Note: Use @UsePipes(ValidationPipe) on method instead of using it in the decorator body. It doesn't affect the result, it's just more convenient.

  @Post('single-file')
  @UsePipes(ValidationPipe)
  @FormDataRequest({storage: FileSystemStoredFile})
  @HttpCode(HttpStatus.OK)
  uploadSingleFile(@Body(new ValidationPipe({ transform: true })) singleFileDto: UploadSingleFileDto) {
    console.log(singleFileDto);

    return singleFileDto
  }

Valid request: image Invalid request image

dutchman1990 commented 1 year ago

Thanks this one works, but ended up getting this { "statusCode": 400, "message": "Unexpected end of form" }

controller

Capture

dmitriy-nz commented 1 year ago

You don't need to use FileInterceptor if you use this library

You can move uploaded file from temp directory to uploads dir in your controller.

dutchman1990 commented 1 year ago

Issue has been resolved. @dmitriy-nz thank you for your kind support.

dutchman1990 commented 1 year ago

@dmitriy-nz one last thing can we override this response structure from

{ "statusCode": 400, "message": [ "store_image should have min size of 3bytes", "store_image does not contain a file" ], "error": "Bad Request" }

to

{ "status_code": 400, "message": "Bad Request", "error": [ "store_image should have min size of 3bytes", "store_image does not contain a file" ] }

I have global exception filter but @FormDataRequest seems overrides that filter.