I`m uploading a file using FileInterseptor, but along with the file I also pass some createDto. The problem is that i validate Dto and if something goes wrong the file is saved anyway. I want the file not to be saved if there are problems with validation. Heres the code:
Controller endpoint:
@UseInterceptors(FileInterceptor('file', saveDocumentToStorage))
  @Post()
  async createDocument(
    @UploadedFile() file: Express.Multer.File,
    @Body() createDocumentDto: CreateDocumentDto,
    @AuthUser() user: UserEntity,
  ): Promise<DocumentDto> {
    const document = await this._documentsService.createDocument(
      file.path,
      createDocumentDto,
      user,
    );
    return document.toDto();
  }
createDto:
export class CreateDocumentDto {
  @IsString()
  @IsNotEmpty()
  readonly name: string;
  @IsString()
  @IsNotEmpty()
  readonly description: string;
}
Thanks for any help
I know that my answer is quite late, but maybe it will help someone. In order to validate data in the request using Dto you need to pass ValidationPipe into the @Body like this:
 @UseInterceptors(FileInterceptor('file', saveDocumentToStorage))
  @Post()
  async createDocument(
    @UploadedFile() file: Express.Multer.File,
    @Body(new ValidationPipe()) createDocumentDto: CreateDocumentDto,
    @AuthUser() user: UserEntity,
  ): Promise<DocumentDto> {
    ...
  }
Here's a link to the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With