Querying structure

A structure to encapsulate and organize these functionalities, as we're already used to.

We can further improve pagination:

  • In the PaginationDto, send the page directly and then calculate the offset

  • Set max values for limit and page, as to avoid a bottleneck

  • Apart from the records, also return a meta field including:

    • itemsPerPage - Amount of items per page

    • totalItems - Total amount of items

    • currentPage - Number of the current page

    • totalPages - Total amount of pages

    • hasNextPage - Existence of a next page

    • hasPreviousPage - Existence of a previous page

Some fields' names were obtained from this package.

Well, before delving deeper into this journey, let's first create a structure to house everything related to pagination/filtering/sorting. As data related to this is generally received as query params, I'll create a folder inside src called querying.

After that, let's relocate here what already exists related to this context. So, relocate the pagination.dto file into querying -> dto. Let's also relocate the DefaultPageSize constant to querying -> util -> querying.constants.

Commit - Relocating querying structure

Let's then begin. Back in the PaginationDto, alter the name of offset to page. While using the offset, we did not need to worry about it not being sent. However, if the page is not sent, it should have a default value, as the offset will be calculated from it.

readonly page?: number = 1;

Sending the page directly avoids the possibility of an inconsistent offset.

Let's also set max values for limit and page, avoiding the possibility of requesting a page with huge size or too far ahead. We do this because this is a limitation of the offset-based pagination: without these precautions, it may be very costly and inefficient. In practice, a customer would not commonly reach these limits. Let's then add them to the querying.constants file.

export const MAX_PAGE_SIZE = 100;
export const MAX_PAGE_NUMBER = 25;

We may then, in the PaginationDto, set the max value to limit...

@Max(MAX_PAGE_SIZE)

...and to page.

@Max(MAX_PAGE_NUMBER)

Commit - Sending page directly and max values in pagination dto

We may then proceed. Let's create a module to hold services related to querying, beginning with a service for pagination.

nest g mo querying
nest g s querying/pagination --flat

Remember to export the service, and import the module in the ProductsModule.

With this structure, we may start the metadata generation.

Last updated