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 thepage
directly and then calculate theoffset
Set max values for
limit
andpage
, as to prevent a bottleneckApart from the records, also return a
meta
field 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 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 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.
Sending the page
directly prevents the possibility of sending an offset
that is inconsistent with the limit
(should be a multiple of it).
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.
We may then, in the PaginationDto
, set the max value to limit
...
...and to page
.
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.
Remember to export the service, and import the module in the ProductsModule
.
With this structure, we may start the metadata generation.
Last updated