Created
November 24, 2023 19:44
-
-
Save rafaelchuluc-nomad/1ab6be0537d2e21920ab9f276ec51fc1 to your computer and use it in GitHub Desktop.
NestJS pagination Decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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