@speles7172/controls-client
v0.2.0
Published
The backend half of @speles7172/controls — searchable, paged option sources over Postgres, and the date range vocabulary both halves resolve, through an executor you supply.
Readme
@speles7172/controls-client
The backend half of @speles7172/controls. One idea: an option
source.
A searchable control needs three things from a server and no more — the options matching what was typed, the options behind what is already chosen, and how many there are in total. All three are the same query with a different ending. You describe the source once, in code, and this compiles them.
npm install @speles7172/controls-clientRequires Node 22+ and Postgres. No database dependency of its own — you supply the executor.
Describing a source
import { createOptionSource } from '@speles7172/controls-client';
const vendors = createOptionSource(pool.query.bind(pool), {
table: 'vendors',
value: 'id',
label: 'name',
description: 'email', // the second line, so two "Acme"s are tellable apart
search: ['name', 'email'], // what people actually type
valueType: 'uuid', // keeps the index usable — see below
where: 'deleted_at IS NULL',
scope: ['org_id'], // narrowable per request, by the endpoint
});Everything that names a table, a column or an ordering lives here. Nothing a request carries can change it.
Serving it
import { optionQueryFromQuery, resolveValuesFromQuery } from '@speles7172/controls-client';
router.get('/options/vendors', async (req, res) => {
// The scope comes from the session, never from the query string.
const scope = { org_id: req.session.orgId };
res.json(await vendors.search(optionQueryFromQuery(req.query), scope));
});
router.get('/options/vendors/resolve', async (req, res) => {
const scope = { org_id: req.session.orgId };
res.json({ options: await vendors.resolve(resolveValuesFromQuery(req.query), scope) });
});Those two endpoints are exactly the OptionTransport the control expects.
The executor
type QueryExecutor = (sql: string, params: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;A pg.Pool, @speles7172/sql-client, a Lambda proxying into a VPC, a
connection borrowed from an ORM — all of them can produce this, and requiring
any one of them would exclude the rest. It is the same shape
@speles7172/audit-client takes, so an application that has one already passes
the same value.
Why it is built the way it is
Ranking, not filtering. A search for ac puts Acme above Pinnacle.
ORDER BY label does not, and the result feels broken in a way nobody can quite
name. The SQL scores matches in the same tiers core/match.ts scores them in
JavaScript, so a static list in the browser and a server-backed one agree about
what the best match is.
resolve applies the same where and scope as search. Not tidiness: a
resolve that skipped them would be an oracle for whether a given id exists in
another tenant and what it is called.
An undefined scope value is refused, not ignored. An org_id that arrived
undefined because a session lookup returned nothing must not quietly become
"every organisation" — that is a tenancy leak that looks exactly like a working
feature.
A scope set on the source is a binding, not a default. A per-call scope may add columns the source left open, but naming a bound one with a different value is refused: a source built as "the vendors of org 1" cannot be argued into being the vendors of org 2. Build a second source if that is genuinely what you want. Resolving it either way silently would be the bug — preferring the call breaks the binding, and preferring the source ignores a narrowing the caller believed had been applied.
valueType exists for the index. Resolving forty ids with
id::text = ANY($1::text[]) casts every row in the table before it can compare,
so the primary key index is unusable and a label lookup becomes a sequential
scan. Declaring the type casts the forty-element array instead. It also filters
out values the column could not hold — one malformed uuid does not return no
rows, it aborts the statement and loses every other label with it.
hasMore is free; total is not. The page query asks for one row more than
it needs. A count over the same predicate is a second query and often the slower
one, so it only runs when includeTotal asks.
Identifiers are a closed grammar. Table and column names are the only strings
that reach SQL uninterpolated — Postgres has no placeholder for an identifier —
so they must match ^[a-z_][a-z0-9_$]*$, optionally as schema.table. Refusing
my table outright beats quoting rules everyone has to remember.
where is author-supplied SQL. It belongs beside the source definition, in
your repository. Never build it from a request; use scope, which binds
parameters. The semicolon check is a tripwire, not a sanitiser.
Date ranges
The other half of <DateRangeFilter>. A browser sends the value —
this_month, last:7d, custom:2026-01-01..2026-02-15 — and never the
instants, because instants resolved in a page are stale by the time they arrive
and wrong for whoever the link is forwarded to.
import { dateRangeFromQuery } from '@speles7172/controls-client/core';
import { compileDateRange } from '@speles7172/controls-client';
const range = dateRangeFromQuery(req.query) ?? { kind: 'preset', preset: 'this_month' };
const filter = compileDateRange('created_at', range, {
timeZone: req.session.timeZone, // the session's, never the browser's
calendar: req.session.calendar, // 'gregorian' | 'hebrew'
startIndex: 2,
});
await pool.query(
`SELECT * FROM invoices WHERE org_id = $1 AND ${filter.text}`,
[orgId, ...filter.params],
);The range is half-open, a day is a civil day in a named zone rather than 86.4
million milliseconds, and an unbounded range compiles to TRUE rather than to
an empty string. core also holds the Hebrew calendar the filter counts months
in, and the fixed-day and time-zone arithmetic underneath both. See
docs/DATES.md.
Entry points
| Import | Contains |
|---|---|
| @speles7172/controls-client | The Node entry: the source, the SQL compiler, the identifier guards. |
| @speles7172/controls-client/core | Dependency-free: the Option/OptionQuery contract, normalisation, query-string parsing, client-side ranked matching, and the date range vocabulary — its resolution, the Hebrew calendar, and the civil-day arithmetic. This is the entry a browser bundle resolves. |
Both are published as ESM and CommonJS.
Licence
MIT
