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 thepagedirectly and then calculate theoffsetSet max values for
limitandpage, as to prevent a bottleneckApart from the records, also return a
metafield including:itemsPerPage- Amount of items per pagetotalItems- Total amount of itemscurrentPage- Number of the current pagetotalPages- Total amount of pageshasNextPage- Existence of a next pagehasPreviousPage- Existence of a previous page
Some fields' names were obtained from the package nestjs-paginate.
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 with Right click -> Refactor -> Move to file.
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;Let's also set max values for limit and page, preventing the possibility of requesting a page with huge size and 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 if both values are too big. 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 --flatWith this structure, we may start the metadata generation.
Last updated