Strapi V4 controllers customization

I was able to add a pagination handler to custom controllers. Adding it here in case someone comes looking in the future:

1. Add the pagination logic to get – a) total count, b) page size, c) page count and d) current page. I wanted to call the items exactly as default so I don’t have to muck around with the front-end code that was already implemented. Added all of this to the meta that would be returned by the controller:

      params._limit = params._limit || 25; // Set the default limit to 25
      params._start = params._start || 0; // Set the default start to 0
      params._sort = params._sort || 'publishedAt:DESC'; // Set the default sort to publishedAt:DESC

2. Now populate the meta:

const meta = {
        total: collection.length, // gets the total number of records
        pageSize: params._limit, // gets the limit we set earlier
        pageCount: Math.ceil(collection.length / params._limit), // gives us the number of total pages
        currentPage: params._start / params._limit + 1, // returns the current page      
      };

3. Include the meta to be returned along with whatever else you are returning, like so:

return { something_you_return, meta };

I hope this helps! BTW, I am learning Strapi new as well! Love it!

[Edit: Simplified the code]

1 Like