Find and count

Bring the entities together with their total count.

We already have the pagination functionality. It would be interesting if we could, apart from bringing the paginated result, also bring the total item count. With this, it would be possible to determine if there is a next page or if the search is already at the end, for example. To achieve this is very simple. We just need to go back to the findAll() method in the ProductsService and replace the repository's find() call with findAndCount().

With this, we can already see the elements of the page and the total count. However, the result is a bit messy, don't you think? It's all mixed up in a single array. Luckily, to solve this is too very simple. If you hover the cursor over the findAndCount() method, you'll notice that it returns an array with two elements. We can then use the following syntax to extract these two elements into their own fields:

const [data, count] = await this.productsRepository.findAndCount({
  // Pagination data
});

return { data, count };

Commit - Incrementing pagination with total count

Last updated