Skip to content

@xtandard/lib/filters/postgrest

Renders the compiled filter AST to PostgREST / Supabase query parameters (no driver dependency): col=op.value pairs for a plain fetch (new URLSearchParams(params)), or applied to a postgrest-js / supabase-js builder with applyParamsToPostgrest.

eq/ne/lt/… → eq./neq./lt.; inArray → in.(…); null checks → is.null / not.is.null; contains/startsWith/endsWith → ilike with * wildcards (the user’s %/_/\ escaped); array ops → cs/cd/ov with a Postgres array literal. or/not groups → or=(…) / not.and=(…), with values double-quoted when they hold a reserved character (, . : * ( )). PostgREST turns every * in a LIKE pattern into %, so a pattern with a literal * falls back to match/imatch (POSIX regex). Sorting → buildOrder (order=col.desc.nullslast), keyset pagination → createPostgrestKeyset.

import { buildParams, textField, numberField } from "@xtandard/lib/filters/postgrest";
const spec = { name: textField({ column: "name" }), amount: numberField({ column: "amount" }) };
const { params } = buildParams({ spec, filters, resolveDate });
// params → [["name", "ilike.*ab*"], ["amount", "gte.100"]]
const res = await fetch(`${POSTGREST_URL}/tasks?${new URLSearchParams(params)}`);
// or with supabase-js: applyParamsToPostgrest(supabase.from("tasks").select(), params)
import { … } from "@xtandard/lib/filters/postgrest";
Name Summary
applyFiltersToPostgrest Compile filters with buildParams and add them to a postgrest-js / supabase-js query via applyParamsToPostgrest. When no filter survives the allow-list, nothing is called. Returns the same builder for chaining.
applyParamsToPostgrest Add PostgrestParams (from buildParams, buildFilterNode or a keyset’s where) to a postgrest-js / supabase-js query with its public methods: a column param becomes .filter(column, operator, value), or=(…) becomes .or(…), and an and=(…)/not.or=(…) param is wrapped as a one-element .or("and(…)"). Returns the same builder for chaining. Works with any object that has filter and or, so this module never imports @supabase/postgrest-js.
buildFilterNode Compile a recursive and/or/not FilterNode tree into PostgREST query parameters. Same allow-list rules as buildParams; values inside or=(…)/and=(…) are double-quoted when they contain a reserved character.
buildOrder Render a Sort to PostgREST order terms, allow-listed to columns (public field name → column). Unknown fields are dropped; when nothing is left, defaultSort is used instead. nulls pins where NULLs go for every term (default: Postgres’s — last ascending, first descending). Apply with query.order(t.column, t) per term (postgrest-js / supabase-js) or as order=${formatOrder(order)}.
buildParams Compile a flat, AND-combined list of column filters into PostgREST query parameters. Only fields in spec whose kind matches the filter’s kind are kept; the rest are silently dropped (params is [] when nothing survives). A date preset filter needs resolveDate (it throws without one).
createPostgrestKeyset Build a keyset (cursor) helper from a sort spec + the PostgREST column each logical key maps to. The last sort column MUST be unique (a tiebreaker like id) so the cursor is stable. orderBy(direction) gives the order terms ("backward" flips every column) and where(cursor, direction) the lexicographic seek as PostgREST params ([] for the first page). Sort keys without a column in columns are skipped. Combine with buildParams output (PostgREST ANDs every param) and limit=pageSize + 1.
formatOrder Serialize order terms to the value of PostgREST’s order query parameter (column.asc|desc[.nullsfirst|.nullslast], comma-separated), or undefined when empty.
toPostgrestParams Render an already-compiled CompiledWhere AST (from compileFilters / compileFilterNode in @xtandard/lib/filters) to PostgREST query parameters, looking each field up in columns. Conditions on fields missing from columns are dropped; null (or an AST that drops to nothing) gives []. A top-level and becomes one param per condition (PostgREST ANDs them); or → or=(…), a negated group → not.or=(…)/not.and=(…), a negated condition → the not. operator prefix. Most code calls buildParams, which compiles and renders in one step.
Name Summary
PostgrestKeyset The keyset helper returned by createPostgrestKeyset.
Name Summary
PostgrestFieldSpec One allow-listed field: its filter kind plus the PostgREST column it reads ("name", or a JSON path such as "meta->>city").
PostgrestFilterBuilder Minimal structural postgrest-js / supabase-js filter builder (no @supabase/* import).
PostgrestFilterSpec A resource’s filter allow-list: public field name → PostgrestFieldSpec.
PostgrestOrderTerm One order term. Its fields line up with postgrest-js: query.order(term.column, { ascending: term.ascending, nullsFirst: term.nullsFirst }). nullsFirst is omitted when the Postgres default applies (NULLs last ascending, first descending).
PostgrestParams PostgREST query parameters as unencoded [key, value] pairs, in order (keys may repeat; PostgREST ANDs them). Pass to new URLSearchParams(params) for a plain fetch, or to applyParamsToPostgrest for a postgrest-js / supabase-js builder.
Name Summary
arrayField Allow-list a public field as an array filter over a Postgres array column (text[], int[]). arrayContains → cs (@>), arrayContained → cd (<@), arrayOverlaps → ov (&&), each with a Postgres array literal whose string elements are always quoted.
booleanField Allow-list a public field as a boolean filter (eq/ne/null checks) over a PostgREST column.
dateField Allow-list a public field as a date filter over a PostgREST column (timestamptz/date). A date preset needs the resolveDate you pass to buildParams, and becomes a half-open gte/lt window with ISO-8601 instants.
enumField Allow-list a public field as an enum filter (eq/ne/inArray/notInArray/null checks) over a PostgREST column. List values containing PostgREST reserved characters are double-quoted (and "/`` backslash-escaped).
numberField Allow-list a public field as a number filter over a PostgREST column. between becomes gte + lte (two params on the same column, which PostgREST ANDs).
textField Allow-list a public field as a text filter over a PostgREST column. contains/ startsWith/endsWith become ilike with * wildcards (the user’s %, _ and \ are escaped); like/ilike patterns are passed through with % spelled *. A literal * can’t be written in a PostgREST LIKE pattern, so those fall back to match/imatch (POSIX regex).