Paginated Endpoint with Version and Error Contract
Spot the off-by-one bug in an offset-based pagination handler serving a versioned REST API.
Codejavascript
// GET /v1/orders?page=1&limit=20
app.get('/v1/orders', async (req, res) => {
const page = Math.max(1, parseInt(req.query.page) || 1);
const limit = Math.min(100, parseInt(req.query.limit) || 20);
const offset = page * limit;
try {
const { rows, total } = await db.getOrders({ offset, limit });
res.json({
data: rows,
page,
limit,
totalPages: Math.ceil(total / limit)
});
} catch (err) {
res.status(500).json({
error: { code: 'INTERNAL', message: 'Something went wrong' }
});
}
});What is the bug in this pagination handler?