How to implement pagination in nodejs + postgresql

陌路散爱 提交于 2020-01-13 10:22:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/48298555/how-to-implement-pagination-in-nodejs-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!