Reputation: 642
I have two routes: /news
and /news-paginate
(I know it is a not good URL but it doesn't matter atm). In the news
route, I load 5 records from the database and render a populated view. In the /news-paginate
route, I load other 5 records based on the page number and size sent from the client; this route responds with a JSON object.
news route
router.get('/news', function (req, res) {
...
connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
res.render('news', {news: rows});
});
});
news-paginate route
router.get('/news-paginate', function (req, res) {
var language = 'RU';
var pageSize = req.query.pageSize;
var pageNumber = req.query.pageNumber;
var offset = (pageNumber - 1) * pageSize;
connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
res.json(rows);
});
});
I am concerned about my architecture. Is my approach correct? I have two routes with the same functionality and different responses. Should I somehow combine these two routes into one?
Upvotes: 0
Views: 1128
Reputation: 2129
Hmm, I usually have a single route, in your case /news
which can receive 2 optional params: pageSize
, pageNumber
for your pagination purposes. If those params don't exists than you will offer the first 5 records. If those params are present than you will start providing the other 5 records and based on the calculated offset
.
router.get('/news/:pageSize?/:pageNumber?', function (req, res) {
var language = 'RU';
var pageSize = req.params.pageSize || 5;
var pageNumber = req.params.pageNumber || 1;
var offset = (pageNumber - 1) * pageSize; // If no params are provided than the offset should be 0
connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
res.json(rows);
});
});
I am not familiar with optional params in express routes
but I hope you get the main idea behind the approach.
You can do ajax requests to load the extra records after the first 5 records are listed.
I hope this shined a light on the approach.
Upvotes: 2