Swagger documentation with multipart/form-data and @ApiImplicitBody

Viewed 9454

I'm trying to create a controller action, which has to upload some files and saves them with some strings into the database. For upload files I use FileFieldsInterceptor and for other data strings DTO. It works. But I want document this endpoint by swagger and it doesn't work. For files, I can use @ApiImplicitFile with @ApiConsumes('multipart/form-data'), but for other body parameters I try use @ApiImplicitBody decorator and the app crashes with an error in api-parameters.explorer.js.

How can I document a body parameter (other than file) into multipart/form-data by @nestjs/swagger module ?

@Post()
@ApiOperation({ ...config.api.post })
@ApiConsumes('multipart/form-data')
@ApiImplicitFile({ name: 'file', required: true, description: 'Infographic file' })
@ApiImplicitFile({ name: 'file_preview', required: true, description: 'Infographic preview file' })
@ApiImplicitBody({ name: 'name', required: true, description: 'Infographic title', type: 'string' })
@UseInterceptors(FileFieldsInterceptor([
        { name: 'file', maxCount: 1 },
        { name: 'file_preview', maxCount: 1 },
    ],
    {
        storage: storageUpload('infographics'),
        limits: {
            fileSize: 20971520, // 20Mb
        },
        fileFilter: (req, file, cb) => {
            const mimeTypeList = ['image/png', 'image/jpeg', 'application/pdf'];

            return mimeTypeList.some(item => item === file.mimetype)
                ? cb(null, true)
                : cb(null, false);
        },
    },
  ), new FilesValidationInterceptor())
upload(@UploadedFiles() files, @Body() createDto: CreateInfographicsDto) {
    return this.infographicsService.create(files, createDto);
}
1 Answers

Error

You have to use String instead of 'string' for the type:

@ApiImplicitBody({ name: 'name', description: 'Infographic title', type: String })
                                                                         ^^^^^^


Form Data

Documenting form-data parameters is not yet supported by @nestjs/swagger according to this github issue. There already exists a pull request that would add this feature but it is not merges yet. You can subscribe to it to get notified when the status updates.

Related