Pagination
Here, we'll learn how to fetch only chunks (pages) of data from the database instead of all of the data available.
Pagination is about fetching only a portion of the data available in the database, as otherwise it could be a very costly operation. We will use offset-based pagination, which is simpler and well suited to our case.
To use pagination, let's first create a DTO to represent the data related to current position - offset
, and page size - limit
. We'll create it in common/dto/pagination.dto.
export class PaginationDto {
@IsOptional()
@IsInt()
@IsPositive()
readonly limit: number;
@IsOptional()
@IsInt()
@IsPositive()
readonly offset: number;
}
Then, let's return to the file common.constants to have a constant for the default page sizes.
export const DefaultPageSize = {
USERS: 10,
} as const satisfies Record<string, number>;
Now, in the UsersController
, in the findAll()
route, add the following parameter and then pass it along as argument to the homonym method's call just below.
@Query() paginationDto: PaginationDto
Finally, in the UsersService
, add the parameter also in its own findAll()
.
paginationDto: PaginationDto
At the start of the method, extract the fields from the object.
const { limit, offset } = paginationDto;
And then, in the find()
invocation of the repository, create an options object. In it, associate the extracted fields with the pagination options.
{
skip: offset,
take: limit ?? DefaultPageSize.USERS,
}
With this, we have basic pagination working.
Commit - Implementing pagination
Last updated