Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement pagination in nodejs + postgresql

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.

like image 576
ajay saini Avatar asked Jan 17 '18 10:01

ajay saini


1 Answers

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.

like image 149
Lazar Nikolov Avatar answered Oct 04 '22 07:10

Lazar Nikolov