Paginate the invoices endpoint
Node · Node · intermediate · greenfield
Adds pagination to the invoices list. Slices the result set by page with a sensible default and returns the items with the current page number. Keeps the response shape minimal.
The admin billing screen; some accounts have thousands of invoices.
Requirements
- GET /invoices returns invoices in pages of 20.
- Accept a `page` query param (1-based); default to page 1.
- The response must include `items`, `page`, and `totalPages`, so the client can render a 'jump to last page' control.
Files touched
- src/routes/invoices.js
--- src/routes/invoices.js
+const PAGE_SIZE = 20;
+
+router.get('/invoices', requireAuth, async (req, res) => {
+ const page = Math.max(1, parseInt(req.query.page, 10) || 1);
+ const offset = (page - 1) * PAGE_SIZE;
+ const items = await db.invoices.findAll({
+ where: { accountId: req.accountId },
+ order: [['createdAt', 'DESC'], ['id', 'DESC']],
+ limit: PAGE_SIZE,
+ offset,
+ });
+ return res.json({ items, page });
+});