I am novice in Node.js. I want to implement pagination in my Api writing in Node.js using express as a framework and Postgresql as database. I want to get the data in form of pagination.
Thanks in advance.
You can use LIMIT and OFFSET in order to get chunks of data from the database. You need 2 variables to do the pagination, page and itemsPerPage. You'd get the page variable from the route itself, for example /api/items/:page, and for the itemsPerPage, you can make it default 20 items for example, but allow the clients to specify it through a query ?items=50 or the request body or a header or however you want. Then when you have both variables you can perform the query on the database, like:
SELECT * FROM items LIMIT {itemsPerPage} OFFSET {(page - 1) * itemsPerPage}
LIMIT means retrieve me X number of items, OFFSET means skip Y items. Both of them combined would be: "skip Y items and get me the next X items". Page - 1 means if you're on the 1st page we don't want to skip any items, but retrieve the first X items. This is valid when the page number is >= 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With