All files / src/common/pagination pagination.dto.ts

0% Statements 0/19
0% Branches 0/4
0% Functions 0/4
0% Lines 0/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                                                                                                 
import { IsInt, IsOptional, Max, Min } from 'class-validator';
import { Type } from 'class-transformer';
 
export class PaginationDto {
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  page?: number = 1;
 
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(200)
  limit?: number = 20;
 
  @IsOptional()
  sortBy?: string;
 
  @IsOptional()
  sortOrder?: 'asc' | 'desc' = 'asc';
}
 
export interface PaginatedResult<T> {
  data: T[];
  meta: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };
}
 
export function buildPaginatedResult<T>(
  data: T[],
  total: number,
  page: number,
  limit: number,
): PaginatedResult<T> {
  const totalPages = Math.ceil(total / limit);
  return {
    data,
    meta: {
      page,
      limit,
      total,
      totalPages,
      hasNextPage: page < totalPages,
      hasPrevPage: page > 1,
    },
  };
}
 
export function paginationToSkipLimit(pagination: PaginationDto): {
  skip: number;
  limit: number;
} {
  const page = pagination.page ?? 1;
  const limit = pagination.limit ?? 20;
  return { skip: (page - 1) * limit, limit };
}