Skip to content

Relations ​

Load related resources alongside the primary one, and unlock their fields for selection, filtering and sorting.

URL keyinclude
AST nodesRelations / Relation { name }
Schema optionsallowed, default, mapping, validate / validateMany

On the wire ​

txt
include=realm,items           comma-separated
include=items.realm           nested path (dot notation)

Parser input shapes:

typescript
{ relations: 'realm,items' }        // comma-separated string
{ relations: ['realm', 'items'] }   // array
{ relations: ['items.realm'] }      // nested paths

Nested paths automatically include their parents: requesting items.realm includes items too, even when a mapping alias expands to the path.

Building in code ​

typescript
defineQuery<User>({ relations: ['items.realm'] });

// record form works too
defineQuery<User>({ relations: { realm: true, items: { user: true } } });

defineRelations<User>(['realm']);   // standalone fragment

Validation ​

Each requested relation is checked against the schema's allowed list. Nested paths resolve segment by segment through schemaMapping: for items.realm, the items segment must be allowed on the root schema and realm on the schema registered for items.

Relation names must match [a-zA-Z0-9_-] segments separated by dots; anything else is dropped (or throws with throwOnFailure).

Schema options ​

typescript
defineSchema<User>({
    relations: {
        allowed: ['realm', 'items'],
        mapping: { children: 'items' },
    },
    schemaMapping: {
        items: 'item',
        realm: 'realm',
    },
});
OptionDescription
allowedTraversable relation names. Omit to allow all; [] blocks the parameter.
defaultRelations included when the client sends no include. See Default includes.
mappingAlias → relation translation applied before validation.
validate / validateManyPer-request key hooks: may this actor traverse this relation? See below.

Default includes ​

default lists the relations a read includes when the client sends no include (absent, include= or an empty list):

typescript
defineSchema<User>({
    relations: {
        allowed: ['items'],
        default: ['realm'],
    },
});
  • Any include from the client replaces the default, even one naming another relation (include=items reads items only).
  • Entries are root relation names of the schema: a dotted path (realm.owner), a mapping alias or a name outside the relation name grammar is refused with a SchemaError when the schema is defined.
  • Like fields.default, a default entry counts as allowed: the client may also include it explicitly. Being allowed, it also extends the relation allow-list that filters and sorts traversal falls back to (filters.relations and sorts.relations default to relations.allowed). Declaring default on a schema without allowed makes the default the allow-list: every other relation is then refused for includes, filters and sorts alike.
  • Defaults are server-authored and bypass the relations validate / validateMany hooks, the same as the filters and sorts defaults. (The fields hook, by contrast, judges the fields a default expands into the projection, see #1017.) Otherwise a default include acts like an explicit one: it gates fields input addressing a relation, the related schema's field defaults are projected, and a key-value default gets its key gate.
  • The bypass covers the include only. A client filter traversing the same relation still records its traversal for the hooks, so when the hook refuses that relation, the relation is pruned from the query, the default include with it.
  • A client cannot ask for "no includes" while a default exists: a blank include reads as absent and gets the default.
  • Only the root schema of a parse applies its default; a related schema's default does not chain.
  • A grouped read hydrates no relation, so it drops a default include no filter traverses, without an error under throwOnFailure.
  • Schema-aware encoding of a query without includes never writes the default onto the wire; the receiving parse applies it. Re-encoding a decoded query writes the default explicitly, since the decoded query carries it as an ordinary include.
  • describe() lists it in relations.default and folds it into relations.allowed.

Key-value relations ​

Operator-defined data (custom attributes stored as (name, value) rows, say) is exposed as one map under a relation, attributes: { department: 'sales', beta: true }. Its names are created at runtime, so the schema cannot list them. Declare the relation as key-value on the root schema of the query:

typescript
defineSchema<User>({
    name: 'user',
    relations: {
        allowed: ['attributes'],
        keyValue: ['attributes'],
    },
});

A key-value relation is still a relation: it must be permitted like any other (allowed, or a filters relations list) and passes the relation hooks. It needs no registered schema. A relation a schema declares as key-value is key-value only where that schema is the root of the query; reached from another root (include=user.attributes on a user_role query) it is refused for every parameter, even when a registered schema is mapped to it. describe() lists it in relations.keyValue and not in relations.schemas.

The key is everything after attributes., dots included: attributes.app.theme names the key app.theme. A key is data, not a column name, so its segments take a wider grammar: letters, digits and _, plus - and : anywhere but the first or last character ([A-Za-z0-9_](?:[A-Za-z0-9_:-]*[A-Za-z0-9_])?). app-theme, 2fa, oidc:sub and x-request-id are all addressable, in all three dialects. A segment named __proto__, constructor or prototype is refused. A stored key outside that grammar (-x, a b, x/y) cannot be named in fields or filters, while a whole-map read still returns it; keep stored key names to this grammar if clients must address them. In the expression dialect a segment spelled like a keyword of the grammar (eq, in, size, null, …) reads as that keyword, so such a key can only be filtered in the simple or mongo dialect.

RequestResult
include=attributesthe whole map; the relation gate applies
fields[attributes]=department,app.themeonly those keys; it implies the include (the relation gate still applies)
fields[attributes]=-salaryan exclusion-only fieldset: the whole map minus salary
filter[attributes.department]=sales&filter[attributes.location]=berlinone condition per key, each matched on its own row, so the two keys may sit on two different rows
sort=attributes.xrefused with keyNotAllowed (silently dropped in a non-strict parse)
include=attributes.xread as include=attributes: the path below the key-value relation is refused (keyPathNotAllowed, dropped in a non-strict parse) and its parent include is kept
sort=attributesrefused with keyNotAllowed: a map has no order
fields=attributes, filter[attributes]=…refused with keyNotAllowed (dropped in a non-strict parse): the bare name is no column; address a key as attributes.<key> and the whole map with include=attributes
include=user.attributes (from another root)refused with keyPathNotAllowed, for every parameter: only relations of the root schema can be key-value

Only equality-style operators are served by the backends that read the map from a key-value table; see @rapiq/adapter-typeorm and @rapiq/adapter-sql.

Gating keys ​

One rule gates every key: the parent schema's fields.validateMany / fields.validate hook, which receives the key as attributes.<key>. Filters reach the filters validate hook as a leaf with field: 'attributes.<key>'.

  • Named keys (fields[attributes]=department) are gated at parse time: a key the hook rejects never enters the AST.
  • A whole-map read (include=attributes, or a fieldset of exclusions only such as fields[attributes]=-salary) loads names nobody requested, which the parse-time hook cannot see. The parser therefore binds the same hook, with the same parse context, onto the parsed Relation as its deferred key gate (Relation.keyValueGate). The backends call it on the names they actually loaded, before mounting the map: @rapiq/adapter-typeorm in hydrate, @rapiq/adapter-sql in each load's merge, @rapiq/adapter-memory while projecting.
typescript
defineSchema({
    name: 'user',
    fields: {
        allowed: ['id', 'name'],
        validateMany: (names, actor) => Object.fromEntries(names.map((name) => [
            name,
            name !== 'attributes.salary' || actor.isAdmin,
        ])),
    },
    relations: { allowed: ['attributes'], keyValue: ['attributes'] },
});

At load time the gate keeps a key under the parse-time rule: a truthy verdict accepts it. A condition verdict gates the value of a requested field, so for a loaded key it drops the key, as do a falsy verdict and a key the record omits. The gate is synchronous whenever the hook is. An async hook needs the async entry points: behind parseAsync() / decodeAsync() the gate returns a Promise, which hydrate awaits and merge hands back; behind a synchronous parse() it throws SCHEMA_VALIDATOR_ASYNC_REQUIRES_ASYNC_PARSER when called, as a named key would at parse time. Without a fields hook no gate is bound and the whole map is read.

Where the gate exists and who honours it:

  • Only parser output carries it. defineQuery, a hand-built Query and a standalone relations sub-parser carry none, so a whole-map read of such a query is not gated.
  • A relation the server needs by default belongs in relations.default, which the parser applies and gates. A relation added after parsing with defineQuery + mergeQueries is not gated, the same as server-added fields; see #1017.
  • mergeQueries keeps a gate from either side: merging a server query that names attributes with a parsed client query keeps the client's gate. When both sides carry one, a key survives only if both keep it.
  • Merging a gate bound by a synchronous parse() with one bound by parseAsync() over an async hook throws SCHEMA_VALIDATOR_ASYNC_REQUIRES_ASYNC_PARSER when the combined gate is called, even if the caller awaits it: the synchronous side refuses the async hook. Parse both sides the same way.
  • @rapiq/adapter-typeorm, @rapiq/adapter-sql and @rapiq/adapter-memory honour it. @rapiq/adapter-prisma and @rapiq/adapter-drizzle refuse a relation carrying one with featureUnsupported('relations:key-value-gate'), Prisma's count() included (it serializes through the same execute).
  • The closure captures the request context, so a query carrying one is request-bound: it never reaches the wire, and a parsed Query must not be reused across requests. @rapiq/cache does not share a whole-map read through it (isCacheable answers false); a fieldset naming keys of the relation never consults the gate and stays cacheable.

Two consequences of the rules above:

  • A named key the hook rejects next to an include (include=attributes&fields[attributes]=salary) leaves the fieldset without keys of the relation, so the include reads the whole map, gated: the rejected key stays out, the others the gate keeps are read. Unlike a column level, an emptied key-value fieldset never fails the parse closed (see fields schema options), and without an include it implies none.
  • A mapping alias applies to the head of a key only: an alias whose source is itself a dotted key-value key (mapping: { 'attributes.foo': 'attributes.bar' }) is ignored, and attributes.foo stays the key foo. An alias of the head that lands inside the relation (mapping: { custom: 'attributes.app' }) continues it: custom.salary reads attributes.app.salary.

Read shape ​

A parent without rows reads attributes: {}. A requested key without a row is absent from the map, unlike a flat key-value field, which mounts null.

Validate hooks ​

Allow-lists are static; validate / validateMany decide per request. Every parse/decode call may carry a context (typically the authenticated actor), and the hook answers for each requested relation with that context in hand. The general contract (verdicts, the scope argument, batching, sync/async) lives at Validate hooks and parse context.

typescript
type Actor = { permissions: string[] };

defineSchema<User, Actor>({
    name: 'user',
    relations: {
        allowed: ['realm', 'items'],
        // may THIS actor include THIS relation? A missing context
        // must be rejected explicitly: it does not fail closed on
        // its own.
        validate: (relation, actor) => !!actor && actor.permissions.includes(`${relation}_read`),
    },
    schemaMapping: { items: 'item' },
});

const query = parser.parse(input, { schema: 'user', context: actor });

The hook runs on the canonical (alias-mapped) relation name against the schema that governs it: include=items.realm invokes the user schema's hook with items and the item schema's hook with realm. A relation is not a column, so an ICondition verdict has nothing to gate and counts as a rejection.

Two rules make the gate hard to bypass:

  • Traversal counts. The hook also gates relations reached through dotted filter, field and sort keys (filter[items.id], fields[items], sort=items.name), which the backends would otherwise auto-join. It runs once per distinct relation across the whole query, so a join has a single authorization point regardless of which parameter forced it.
  • Rejection prunes deep. Rejecting a relation drops every deeper relation reached through it and every dependent key in every parameter, at parse time; the pruned branch never enters the AST. Under throwOnFailure the rejection fails the parse instead, recorded as a KEY_VALIDATE_REJECTED issue for the relations parameter on the trace of the raised inputRejected error.

One thing pruning never drops: a preserve() filter condition. If a filters validate hook preserves a condition that names a relation this hook rejects, the two hooks contradict each other: pruning the condition returns a result set the policy did not describe (a wider one for the usual and(<leaf>, <scope>) residual), keeping it joins a relation the gate refused. Parsing therefore throws a SchemaError with ErrorCode.SCHEMA_PRESERVED_CONDITION_PRUNED rather than picking one. That is a server misconfiguration, not client input: see Authorization. The exception is a residual the filters hook of a related schema attached to a client leaf through this relation (filter[realm.name], judged by the realm schema's hook): the client chose that traversal, so the request fails as client input instead: the leaf is refused with KEY_PATH_NOT_ALLOWED, or, under a throwing policy, the relation rejection itself is raised.

A schema default filter is exempt from pruning: it is the server-authored baseline and is re-applied after the gate has run, even when it names a rejected relation. Preserving a default opts it back into the contradiction check, since it asserts the same must-survive contract as a residual and raises the same error.

Interaction with other parameters ​

Parsed relations feed back into the other parameter parsers: fields input that addresses a relation (items.id, realm.name) is only accepted when the relation was requested and allowed, so request the relation first. Filters and sorts input is gated by the schema's filters.relations / sorts.relations (defaulting to relations.allowed) and does not need the include. A validate hook participates in the same wiring: it also authorizes the relations those keys traverse.

On violation ​

Disallowed or invalid relation input is dropped silently; with throwOnFailure it fails the parse instead (RelationsParseError from parseRelations, the general ParseError from a whole-query parse, each carrying the rejection on its issue trace).

Released under the MIT License.