Skip to content

Add pagination to get multiple quotes #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function getOffset(currentPage = 1, listPerPage) {
return (currentPage - 1) * [listPerPage];
}

function emptyOrRows(rows) {
if (!rows) {
return [];
}
return rows;
}

module.exports = {
getOffset,
emptyOrRows
}
2 changes: 1 addition & 1 deletion routes/quotes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const quotes = require('../services/quotes');
/* GET quotes listing. */
router.get('/', async function(req, res, next) {
try {
res.json(await quotes.getMultiple());
res.json(await quotes.getMultiple(req.query.page));
} catch (err) {
console.error(`Error while getting quotes `, err.message);
next(err);
Expand Down
15 changes: 11 additions & 4 deletions services/quotes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
const db = require('../services/db');
const db = require('./db');
const helper = require('../helper');
const config = require('../config');

async function getMultiple(){
const data = await db.query('SELECT id, quote, author FROM quote');
const meta = {page: 1};
async function getMultiple(page = 1){
const offset = helper.getOffset(page, config.listPerPage);
const rows = await db.query(
'SELECT id, quote, author FROM quote LIMIT ?,?',
[offset, config.listPerPage]
);
const data = helper.emptyOrRows(rows);
const meta = {page};

return {
data,
Expand Down