Implementing pagination queries with TypeORM in NestJS typically follows these steps:
- Create a Data Access Service: Define a method within the service to handle query logic.
- Receive Pagination Parameters: Accept pagination parameters from the client, typically
pageandlimit, wherepagedenotes the current page number andlimitspecifies the number of items per page. - Calculate the Number of Items to Skip: Compute the
skipvalue based on pagination parameters, which indicates the number of items to skip. This is calculated as(page - 1) * limit. - Execute the Query and Return Results: Utilize TypeORM's
findAndCountorcreateQueryBuildermethods to execute the pagination query and compute the total count.
Below is a concrete example:
typescriptimport { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { YourEntity } from './entities/your.entity'; @Injectable() export class YourService { constructor( @InjectRepository(YourEntity) private readonly yourEntityRepository: Repository<YourEntity>, ) {} async paginate(page: number = 1, limit: number = 10) { // Calculate the number of items to skip const skip = (page - 1) * limit; // Execute query and return results with total count const [results, total] = await this.yourEntityRepository.findAndCount({ take: limit, skip: skip, // Add other query conditions and sorting as needed // where: { ... }, // order: { ... }, }); // Return pagination results and metadata return { data: results, // Current page data count: total, // Total number of items currentPage: page, // Current page number totalPages: Math.ceil(total / limit), // Total pages }; } }
In this example, the paginate method in the YourService service accepts two parameters, page and limit, corresponding to the client's request for the current page number and items per page. The method uses findAndCount to execute the query and compute the total count, then returns an object containing the current page data, total count, current page number, and total pages.
Practically, you should handle edge cases such as verifying that page and limit are positive integers and that page does not exceed the total pages. Additionally, incorporate sorting and filtering conditions as needed to meet specific business requirements.