Documenting files routes

Integrating the files routes with swagger.

Routes that handle files require manual documentation in Swagger, but nothing too compex. In the uploadImages() route, two decorators should be employed:

  • @ApiConsumes() - Receives the format of the body, in this case it is multipart/form-data

  • @ApiBody() - Receives the type of a file, which will be manually represented in a schema.

First, back in file.constants, let's create a constant for the body format when sending files.

export const MULTIPART_FORMDATA_KEY = 'multipart/form-data';

Then, we'll create two decorators to represent, respectively, a file and an array of files, in swagger. So, let's begin with the first one in files -> swagger -> decorators -> api-file-property.decorator.

export const ApiFileProperty = () =>
  ApiProperty({ type: 'string', format: 'binary' });

This part involves the syntax of the Swagger schema. I recommend these official docs as a further read, if desired.

And then the next one, in api-files-property.decorator.

export const ApiFilesProperty = () =>
  ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } });

We created them in order to more easily create the schemas to map files. And that's exactly what we'll do now, so create the file files -> swagger -> schemas -> file.schema.

export class FileSchema {
  @ApiFileProperty()
  file: Express.Multer.File;
}

And also, the file files.schema.

export class FilesSchema {
  @ApiFilesProperty()
  files: Express.Multer.File[];
}

We have all the necessary pieces in hand. We can then go back to the ProductsController and make the adjustments. Over the uploadImages() route, add these decorators:

@ApiConsumes(MULTIPART_FORMDATA_KEY)
@ApiBody({ type: FilesSchema })

And, to indicate that the downloadImage() route returns a file, add over it:

@ApiOkResponse({ type: FileSchema })

And we're done, the lacking documentation was added to the file-related routes.

Commit - Integrating file routes with swagger

Last updated