#Make file optional along with other payload

2 messages · Page 1 of 1 (latest)

keen tide
#
  @ApiBearerAuth()
  @Post('meal')
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file'))
  createMeal(
    @UploadedFile(
      new ParseFilePipeBuilder()
        .addMaxSizeValidator({
          maxSize: 1024 * 1024 * 5, // 5MB
        })
        .build(),
    )
    file: Express.Multer.File | undefined, // Indicate that the file can be undefined
    @Request() req,
    @Body() createMealDto: CreateMealDto,
  ) {
    console.log(file);
    console.log(createMealDto);

    if (file) {
      // Do something with the file, if provided
    }

    return 'this.mealsService.createMeal(createMealDto, req.user.email);';
  }```

dto
```export class CreateMealDto {
  @IsString()
  @ApiProperty()
  name: string;
  @IsString()
  @ApiProperty()
  description: string;
  @IsString()
  @ApiProperty()
  price: number;

  @IsString()
  @ApiProperty()
  mealCategoryId: number;

  @ApiProperty({ type: 'string', format: 'binary', required: false })
  file: Express.Multer.File;
}```

This works but the file is required if i try to send it via swagger. How can i make it not required?
boreal cipher
#

I believe if you use FileInterceptor you have to send a file. For optional, I think you have to use AnyFileInterceptor, but then you use @UploadedFiles() and need to validate/verify the files that are uploaded as it can be more than one