Skip to content

Instantly share code, notes, and snippets.

@rafaelchuluc-nomad
Created November 24, 2023 19:44
Show Gist options
  • Save rafaelchuluc-nomad/1ab6be0537d2e21920ab9f276ec51fc1 to your computer and use it in GitHub Desktop.
Save rafaelchuluc-nomad/1ab6be0537d2e21920ab9f276ec51fc1 to your computer and use it in GitHub Desktop.
NestJS pagination Decorator
import { ExecutionContext, createParamDecorator } from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';
export interface IPagination {
page: number;
limit: number;
}
export interface IPaginationResponse<T> {
items: T[];
totalItems: number;
currentPage: number;
totalPages: number;
itemsPerPage: number;
}
export const Paginate = createParamDecorator(
(_data: unknown, context: ExecutionContext) => {
const req = context.switchToHttp().getRequest();
const { page, limit } = req.query;
return {
page: page ? Number(page) : 1,
limit: limit ? Number(limit) : 10,
};
},
[
(target: any, key: string) => {
ApiQuery({
name: 'page',
schema: { default: 1, type: 'number', minimum: 1 },
required: false,
})(target, key, Object.getOwnPropertyDescriptor(target, key));
ApiQuery({
name: 'limit',
schema: { default: 10, type: 'number', minimum: 1 },
required: false,
})(target, key, Object.getOwnPropertyDescriptor(target, key));
},
],
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment