Metadata field
Useful data about pagination.
In the PaginationService
, let's first create a method to calculate the offset
from the limit
and page
. In the first page
, no items are skipped. And for each page
after the first one, we should skip the same amount of items as in limit
. With this, offset
will always be consistent.
Then, before creating the method which will create the meta
field, let's first create an interface to represent this metadata in querying/interfaces/pagination-meta.interface.
And finally, the method that creates the meta
field. Its steps are:
Calculate the page count, dividing the item count by the page size, and rounding it up in case of a decimal result (last page with fewer items)
Check if the current page is greater than the last page, in such case no metadata will be returned
Define if there are next/previous pages from the current page
Return all the metadata
What remains to be done now is to inject the PaginationService
in the ProductsService
, and adjust the logic of the findAll()
method.
We can then do the same with the remaining findAll()
methods to finish this part of pagination.
Commit - Incrementing pagination with metadata field
I recommend this article by Matej Bačo (blog) in case there is interest to learn more about it.
Last updated