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

Optinal property #12

Closed Misir8 closed 2 years ago

Misir8 commented 2 years ago

When updating an entity, I want to make an optional file update. If the user did not add a new file, then leave the old file, and if he added it, then add a new file.

But when I write in the Dto like this:

@IsFile()
@IsOptional()
@MaxFileSize(5e6)
@HasMimeType(['image/jpeg', 'image/png', 'image/jpeg'])
@ApiModelPropertyOptional({ type: 'string', format: 'binary' })
readonly image?: Memory Stored File;

I get an error:

{
  "statusCode": 400,
  "message": [
    "File must be of one of the types image/jpeg, image/png, image/jpeg",
    "Maximum file size is 5000000"
  ],
  "error": "Bad Request"
}
dmitriy-nz commented 2 years ago

I tried to reproduce the problem, everything works as expected, see screenshots. My DTO class

export class AttachmentDto {

  @IsFile()
  @IsOptional()
  @MaxFileSize(5e6)
  @HasMimeType(['image/jpeg', 'image/png', 'image/jpeg'])
  readonly image?: MemoryStoredFile;

}

Send request with image field: Request: Выделение_284 DTO instance in console: Выделение_288 Send request without image field: Выделение_286 DTO instance in console: Выделение_287 it is empty because there are no other fields

Maybe the problem is that you are sending null or any other value in the optional field, then the validator tries to check it. In order for the validator to skip this field, it should not exist in the dto that is sent from the client. Try to check the request through REST Client (postman or insomnia)

Misir8 commented 2 years ago

@dmitriy-nz Thank you very much. I tested only in the swagger ui and always got a validation error there.

dmitriy-nz commented 2 years ago

You're welcome! Please check this if all is well close the issue :relaxed: