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 = {
  USER: 10,
} as const satisfies Record<string, number>;

The satisfies keyword forces a certain typing on an object. In this case, its fields must be of type 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.USER,
}

If offset is not sent, the search will start from the beginning. If limit is not sent, the default page size will be used.

With this, we have basic pagination working.

In a real-world application, when searching for many records in the database, generally there should also be

  • Pagination metadata

  • Filtering and sorting functionality

We'll learn how to implement and architect these features in the Extra module 5 - Advanced Querying.

Commit - Implementing pagination

Last updated