Skip to content

Instantly share code, notes, and snippets.

@MohammedALREAI
Created January 19, 2023 16:48
Show Gist options
  • Save MohammedALREAI/15863e853df57e919ced1ffc3b3f6b50 to your computer and use it in GitHub Desktop.
Save MohammedALREAI/15863e853df57e919ced1ffc3b3f6b50 to your computer and use it in GitHub Desktop.
paginator with Gentaick
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
})
}
@MohammedALREAI
Copy link
Author

how to used it
public async getEventsOrganizedByUserIdPaginated( userId: number, paginateOptions: PaginateOptions ): Promise<PaginatedEvents> { return await paginate<Event>( this.getEventsOrganizedByUserIdQuery(userId), paginateOptions ); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment