Search code examples
expressnestjs

NestJS: Option to make file in endpoint optional


I am using NestJS to create REST API and I am trying to create an endpoint that will require certain body but also accept file that should be optional.

@UseGuards(JwtAuthGuard)
@Post('create')
@UseInterceptors(FileInterceptor('file', { }))
async createPost(@Req() req: any, @Body() createPostDto: CreatePostDto, @UploadedFile(new ParseFilePipeBuilder().addMaxSizeValidator({ maxSize: 2048 }).build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY })) file: Express.Multer.File) {
        return await this.postsService.createPost(req.user, createPostDto, file);
}

But using this code makes the file required at all times as seen in this error response:

{
    "statusCode": 422,
    "message": "File is required",
    "error": "Unprocessable Entity"
}

Is there a way to make the upload file optional?


Solution

  • I found an answer on NestJS discord. I changed ParseFilePipeBuilder to ParseFilePipe which supports fileIsRequired option.

    @UseGuards(JwtAuthGuard)
    @Post('create')
    @UseInterceptors(FileInterceptor('file', { }))
    async createPost(@Req() req: any, @Body() createPostDto: CreatePostDto, @UploadedFile(new ParseFilePipe({
            validators: [
                new MaxFileSizeValidator({ maxSize: parseInt(process.env.MAX_FILE_UPLOAD_SIZE) * 1000 })
            ],
            fileIsRequired: false
        })) file?: Express.Multer.File) {
            return await this.postsService.createPost(req.user, createPostDto, file);
        }