Skip to content

applyKeysetToKnex

function applyKeysetToKnex<TQuery>(
query,
where,
order,
options
): TQuery;

Defined in: pagination-knex.ts:59

Apply a portable keyset WHERE + ORDER BY to a Knex query builder. Values are passed as bindings; column identifiers are validated by the raw SQL helpers before being rendered.

This mutates and returns the provided Knex query builder, matching Knex’s chaining style. For first-page cursor requests (where === null), it skips whereRaw and only applies orderByRaw.

Type Parameter
TQuery extends KnexKeysetQuery
Parameter Type
query TQuery
where | KeysetWhere | null
order KeysetSortKey[]
options ApplyKeysetToKnexOptions

TQuery

import { createKeysetSpec } from "@xtandard/lib/pagination";
import { applyKeysetToKnex } from "@xtandard/lib/pagination/knex";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const q = applyKeysetToKnex(
knex("posts").select("*"),
keyset.where(cursor, direction),
keyset.orderBy(direction),
{ columns: { createdAt: "created_at", id: "id" } },
);
const rows = await q.limit(limit);

If options.columns is missing a key or contains an unsafe SQL identifier.