better-drizzle

Pagination

Use paginate() for offset pages and cursor() for cursor navigation.

paginate() is the offset helper. cursor() is the cursor helper. Both return { data, pagination }, but the metadata is specific to the strategy.

Offset pagination

Use limit (or take) with skip when the consumer needs totals and page numbers:

const {
	data, // User[]
	pagination: { type, page, perPage, total, pageCount, hasNext, hasPrevious }, // type: "offset"
} = await client.users.paginate({
	limit: 20,
	skip: 40,
	orderBy: [{ id: 'asc' }],
	where: { active: true },
});

paginate() reads only three paging inputs:

InputMeaning
limitpage size, default 10
takepage size; wins over limit when both are set
skiprows to skip, default 0

There is no page or perPage input: pass skip: (page - 1) * perPage. In the result, perPage is the resolved page size, page is Math.floor(skip / perPage) + 1, and pageCount is 0 when total is 0.

Cursor pagination

Use cursor() for feed-style navigation:

const {
	data: first,
	pagination: { nextCursor },
} = await client.users.cursor({
	limit: 2,
	orderBy: [{ id: 'asc' }],
});

const { data: second } = await client.users.cursor({
	limit: 2,
	orderBy: [{ id: 'asc' }],
	after: nextCursor as { id: number },
});

Pass before to move backwards. cursor() accepts before or after, never both.

const {
	data: previous,
	pagination: { hasPrevious },
} = await client.users.cursor({
	limit: 2,
	orderBy: [{ id: 'asc' }],
	before: { id: 4 },
});

cursor() page size comes from limit, then take, and defaults to 10. after and before take cursor objects, such as the nextCursor / previousCursor from a previous page. Without orderBy, pages are ordered by primary key ascending.

Cursor pagination needs a stable order

Always pass a deterministic orderBy (typically including a unique column like the primary key) when paginating by cursor, or pages can overlap or skip rows.

Pagination with projection

Both helpers accept the same select / include as a normal read:

const {
	data: page,
	pagination: { total },
} = await client.posts.paginate({
	limit: 10,
	orderBy: [{ id: 'desc' }],
	include: { author: true },
});

const {
	data: feed,
	pagination: { hasNext },
} = await client.posts.cursor({
	limit: 10,
	orderBy: [{ id: 'desc' }],
	include: { author: true },
});

Choosing offset vs cursor

StrategyGood forTrade-off
Offsetadmin tables, reporting, simple listseasy to reason about; weaker on very large, changing datasets
Cursorfeeds, timelines, large mutable datasetsneeds stable ordering and cursor discipline

On this page