'Separate swagger implementation from controller code

I'm trying to document my api in NestJS. I have followed NestJS documentation and it works very well but I would like to know if there is anyway to separate the swagger decorators from the controller code. Because the api starts to grow, the controller code starts to get a little bit confusing because having the decorators in between the request methods interferes with the way the flow it is seen.

I have used the decorators but when you need in an endpoint guards validation, pipes it gets pretty big and unfocused, because of the amount of decorators that get added and I am not confused swagger is not that important in the actual execution flow as it is guards, validators, etc.

@Post()
@Roles('user')
@ApiResponse({ status: 201, description: 'The token has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.'})
@UsePipes(new ValidationPipe())
@HttpCode(200)
async createToken(@Body() createTokenDto: CreateTokenDto) {
  this.tokenBuilderService.createToken(createTokenDto);
}


Solution 1:[1]

No.You can't separate the swagger decorators from the controller code. I usually place it at the end to separate them from pipes and guards:

@Post()
@Roles('user')
@UsePipes(new ValidationPipe())
@HttpCode(201)
@ApiResponse({ status: 201, description: 'The token has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.'})
async createToken(@Body() createTokenDto: CreateTokenDto) {
  this.tokenBuilderService.createToken(createTokenDto);
}

Solution 2:[2]

Pretty old question but just pointing it out so people will know. You can separate using the applyDecorators function imported from @nestjs/common which accepts an array of decorators and composes them for you in a single decorator: https://docs.nestjs.com/custom-decorators#decorator-composition

In your example, you could do something like:

// controller.decorator.ts
export function SwaggerDecorator() {
  return applyDecorators(
    ApiResponse({ status: 201, description: 'The token has been successfully created.' }),
    ApiResponse({ status: 403, description: 'Forbidden.' })
  );
}
Note that the decorators are without the @ symbol.

and import it in the controller file:

import { SwaggerDecorator } from './controller.decorator'

@Post()
@Roles('user')
@SwaggerDecorator()
@UsePipes(new ValidationPipe())
@HttpCode(200)
async createToken(@Body() createTokenDto: CreateTokenDto) {
  this.tokenBuilderService.createToken(createTokenDto);
}

I just faced this issue and it cleared A LOT of swagger code in my controllers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maxim Pyshko
Solution 2 Ariel Fenster