Created
January 19, 2023 16:48
-
-
Save MohammedALREAI/15863e853df57e919ced1ffc3b3f6b50 to your computer and use it in GitHub Desktop.
paginator with Gentaick
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 { Expose } from "class-transformer"; | |
import { SelectQueryBuilder } from "typeorm"; | |
export interface PaginateOptions { | |
limit: number; | |
currentPage: number; | |
total?: boolean; | |
} | |
export class PaginationResult<T> { | |
constructor(partial: Partial<PaginationResult<T>>) { | |
Object.assign(this, partial); | |
} | |
@Expose() | |
first: number; | |
@Expose() | |
last: number; | |
@Expose() | |
limit: number; | |
@Expose() | |
total?: number; | |
@Expose() | |
data: T[]; | |
} | |
export async function paginate<T>( | |
qb: SelectQueryBuilder<T>, | |
options: PaginateOptions = { | |
limit: 10, | |
currentPage: 1 | |
} | |
): Promise<PaginationResult<T>> { | |
const offset = (options.currentPage - 1) * options.limit; | |
const data = await qb.limit(options.limit) | |
.offset(offset).getMany(); | |
return new PaginationResult({ | |
first: offset + 1, | |
last: offset + data.length, | |
limit: options.limit, | |
total: options.total ? await qb.getCount() : null, | |
data | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to used it
public async getEventsOrganizedByUserIdPaginated( userId: number, paginateOptions: PaginateOptions ): Promise<PaginatedEvents> { return await paginate<Event>( this.getEventsOrganizedByUserIdQuery(userId), paginateOptions ); }