nestjs / nestjs/swagger

Registering custom decorators

Open
#32 3 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature request PRs open
Dominant language
TypeScript
Stars
1.9k
Forks
557
Avg merge
2d 47m
Merged PRs (30d)
53

Description

I have a custom decorator for pagination using query strings but I have not been able to get Swagger to pick them up

// pagination.decorator.ts
import {createRouteParamDecorator} from '@nestjs/common';
import config from 'config';
import {Request} from 'express';
import {PaginationOptions} from './pagination.model';

export const Pagination: Function = createRouteParamDecorator(
  (_: string, req: Request): PaginationOptions => {
    req.query.limit = (typeof req.query.limit === 'number') ?
      req.query.limit :
      parseInt(req.query.limit, 10) || config.pagination.size;

    req.query.page = (typeof req.query.page === 'number') ?
      req.query.page :
      parseInt(req.query.page, 10) || 1;

    if (req.query.limit > config.pagination.max) {
      req.query.limit = config.pagination.max;
    } else if (req.query.limit < config.pagination.min) {
      req.query.limit = config.pagination.min;
    }

    const limit: number = req.query.limit;
    const page: number = req.query.page;

    return {
      limit,
      page
    };
  }
);

// pagination.model.ts
import {ApiModelPropertyOptional} from '@nestjs/swagger';

export class PaginationOptions {
  @ApiModelPropertyOptional() public readonly limit: number;
  @ApiModelPropertyOptional() public readonly page: number;
}

// documents.controller.ts
....
  @Get()
  @ApiResponse(swagger.NOCONTENT)
  @ApiResponse(swaggerWithType(swagger.OK, Document))
  public async httpGetAll (
    @Pagination() pagination: PaginationOptions
  ): Promise<PaginateResult<Role>> {
    return this.documentService.readAll(pagination);
  }
....

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with pagination.decorator.ts and documents.controller.ts, then inspect how the Swagger module processes the @Pagination() parameter and the PaginationOptions model in pagination.model.ts. Confirm the desired result by checking generated Swagger output: the pagination query parameters should be represented for the endpoint.

Written by the indexing model from the issue text.

Assessment

Tech stack
express, typescript
Domain
api
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.