I can share with you how my implementation works by using ExpressJS and MySQL database. The ideas behind are:
- Determine the
numberOfRows
of the data that you wish to display form the database.
- Set a
pageSize
to show the number of items to be displayed in single page.
- Always return the
page
number for the current view using req.query
, else by default, it will be page 1.
- By using the returned
page
, we can calculate the number of rows of data to be skip
.
- Lastly, setup the
limit(offset, length)
in your query.
The coding part will be:
var connection;
var pageSize = 20;
var numberOfRows, numberOfPages;
var numberPerPage = parseInt(pageSize,10) || 1;
var page = parseInt(pageInfo.page, 10) || 1;
var skip = (page - 1) * numberPerPage;
var limit = `${skip} , ${numberPerPage}`;
return connectionPool.getConnection()
.then((connect) => {
connection = connect;
return connection.query(`SELECT COUNT(*) AS total ....`); //To get total rows
})
.then(([rows, field]) => {
numberOfRows = rows[0].total;
numberOfPages = Math.ceil(numberOfRows / numberPerPage);
return connection.query(`SELECT .... LIMIT ${limit}`); //Get specific data with LIMIT
})
.then(([rows, field]) => {
result = {
rows: rows,
pagination: {
current: page,
numberPerPage: numberPerPage,
has_previous: page > 1,
previous: page - 1,
has_next: page < numberOfPages,
next: page + 1,
last_page: Math.ceil(numberOfRows / pageSize)
}
}
return result;
})
.catch((err) => {
throw new Error(err.message);
})
.finally(() => {
connection.release();
})
It's a workable code, all you need is just properly organize your returned result
correctly in your pagination at the frontend. Although it is done by using MySQL, but I hope you get the concept behind.