Search code examples
swaggernestjs

NestJS / CrudController Swagger as GetManyBase


how do I decorate a custom method inside my CrudController so that the Swagger documentation would be shown as the one from getManyBase? Meaning I need to have all of the filter fields.

I tried this way

 @Get('/projects')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: Project, isArray: true })
  getManyProjects(@ParsedRequest() req: CrudRequest, @Request() request)
    : Promise<GetManyDefaultResponse<Project> | Project[]> {
    const { id, role } = request.user;
    if (role === UserRoles.User) {
      req.parsed.filter.push({
        field: 'userId',
        operator: 'eq',
        value: id,
      });
    }
    return this.projectService.getMany(req);
  }

but the Swagger docs shows empty for the query parameters, enter image description here

while I'm expecting something like getManyBase. enter image description here

Funny thing is, the method would work properly if I send the filter string, but I need Swagger to display them as well. Advice?


Solution

  • See this area in the nestjsx/crud repo.

    If you add something like this to your constructor that should do it:

    import { Swagger } from '@nestjsx/crud/lib/crud';
    
    ...
    
    constructor() {
        const metadata = Swagger.getParams(this.getManyProjects);
        const queryParamsMeta = Swagger.createQueryParamsMeta('getManyBase');
        Swagger.setParams([...metadata, ...queryParamsMeta], this.getManyProjects);
    }