Add query customization to model pagination

This commit is contained in:
Alice Gaudon 2020-06-14 21:47:51 +02:00
parent 362343171c
commit fa42b8991b

View File

@ -16,9 +16,10 @@ export default abstract class Model {
return models.length > 0 ? models[0] : null; return models.length > 0 ? models[0] : null;
} }
public static async paginate<T extends Model>(request: Request, perPage: number = 20): Promise<T[]> { public static async paginate<T extends Model>(request: Request, perPage: number = 20, query?: Query): Promise<T[]> {
let page = request.params.page ? parseInt(request.params.page) : 1; let page = request.params.page ? parseInt(request.params.page) : 1;
let query: Query = this.select().limit(perPage, (page - 1) * perPage).withTotalRowCount(); if (!query) query = this.select();
query = query.limit(perPage, (page - 1) * perPage).withTotalRowCount();
if (request.params.sortBy) { if (request.params.sortBy) {
const dir = request.params.sortDirection; const dir = request.params.sortDirection;
query = query.sortBy(request.params.sortBy, dir === 'ASC' || dir === 'DESC' ? dir : undefined); query = query.sortBy(request.params.sortBy, dir === 'ASC' || dir === 'DESC' ? dir : undefined);