@arraypress/pagination
v1.0.0
Published
Pagination math and SQL helpers — calculate offsets, page counts, and build paginated responses.
Maintainers
Readme
@arraypress/pagination
Pagination math and SQL helpers. Calculate offsets, page counts, and build paginated API responses. Zero dependencies.
Works in Node.js, Cloudflare Workers, Deno, Bun, and browsers.
Install
npm install @arraypress/paginationFunctions
paginate(options?)
Calculate pagination metadata from page, limit, and total.
import { paginate } from '@arraypress/pagination';
paginate({ page: 3, limit: 20, total: 247 })
// => { page: 3, limit: 20, offset: 40, pages: 13, total: 247, hasNext: true, hasPrev: true }
paginate({ page: 1, limit: 10, total: 5 })
// => { page: 1, limit: 10, offset: 0, pages: 1, total: 5, hasNext: false, hasPrev: false }
// Parses strings (from query params)
paginate({ page: '3', limit: '20', total: 100 })
// Clamps out-of-range values
paginate({ page: 999, limit: 10, total: 50 }) // page clamped to 5
paginate({ page: 0, limit: 10, total: 50 }) // page clamped to 1
paginate({ limit: 500, total: 100 }) // limit clamped to 100 (maxLimit)paginateQuery(sql, options?)
Append LIMIT and OFFSET to a SQL string.
import { paginateQuery } from '@arraypress/pagination';
paginateQuery('SELECT * FROM orders', { page: 3, limit: 20 })
// => 'SELECT * FROM orders LIMIT 20 OFFSET 40'
paginateQuery('SELECT * FROM orders WHERE status = ?', { page: 2, limit: 25 })
// => 'SELECT * FROM orders WHERE status = ? LIMIT 25 OFFSET 25'paginateResponse(items, total, options?)
Build a complete paginated API response object.
import { paginateResponse } from '@arraypress/pagination';
const orders = await db.prepare('SELECT * FROM orders LIMIT ? OFFSET ?').bind(20, 40).all();
const total = await db.prepare('SELECT COUNT(*) as count FROM orders').first('count');
return c.json(paginateResponse(orders.results, total, {
page: c.req.query('page'),
limit: c.req.query('limit'),
key: 'orders',
}));
// => { orders: [...], page: 3, pages: 13, total: 247, limit: 20, hasNext: true, hasPrev: true }parseParams(params?, defaults?)
Parse page and limit from a query params object.
import { parseParams } from '@arraypress/pagination';
// In a Hono route:
const { page, limit } = parseParams(c.req.query());
// With custom defaults:
const { page, limit } = parseParams(c.req.query(), { limit: 50 });Usage with Hono + D1
import { paginate, paginateResponse } from '@arraypress/pagination';
app.get('/api/orders', async (c) => {
const total = await c.env.DB.prepare('SELECT COUNT(*) as count FROM orders').first('count');
const { offset, limit, page } = paginate({
page: c.req.query('page'),
limit: c.req.query('limit'),
total,
});
const orders = await c.env.DB.prepare('SELECT * FROM orders ORDER BY created_at DESC LIMIT ? OFFSET ?')
.bind(limit, offset).all();
return c.json(paginateResponse(orders.results, total, { page, limit, key: 'orders' }));
});License
MIT
