Queries
The operations that add, configure, read back and remove a query, a page route that answers a count, an aggregate or a series of points computed from a resource.
Overview
A query gives a page a count, a total or a series of points to display. This example adds a query to an existing /books page that counts the rows of the book resource:
import { AddQuery } from "@antelopejs/interface-dms-builder";
const result = await AddQuery("/books", {
name: "bookCount",
resource: "book",
template: "count",
});
if (result.ok) {
console.log(result.data.route); // "/dms/pages/books/stats/book-count"
} else {
console.error(result.error);
}
AddQuery writes a model method and a page route. It adds no visible block. After the backend reloads, a signed-in user with access to /books can request the route through the frontend, and the route answers { "value": N }, where N is the number of rows. A block reads the answer through the returned route, as its fetchUrl. An editor that previews before it saves uses PreviewQuery and page drafts instead of a call to AddQuery on each change.
The route carries the page's own permission, through a parameter decorator on that route alone. A user who can open the page can read what the query derives, and no other route on the controller changes.
A query is addressed by a QueryRef, lives on a page, and reads from a resource. A template decides what a query can compute. You pick one by id and fill in its parameters, and the builder emits the database chain.
GetPageStructure reports the queries it finds on a page in PageStructure.queries, whether the builder wrote them or a person did.
Address a query
QueryRef is <pageRef>@<name>, for example /books@inStockCount. The page part says where the route lives. The query itself records the resource it reads, and the ref does not.
import type { QueryRef } from "@antelopejs/interface-dms-builder";
const query: QueryRef = "/books@inStockCount";
List the templates
ListQueryTemplates(resourceType?) returns the templates registered now. It is a plain read of a live registry, so the ids it returns are the ones to use.
import { ListQueryTemplates } from "@antelopejs/interface-dms-builder";
const templates = await ListQueryTemplates("database-table");
for (const template of templates) {
console.log(template.id, template.title, template.output);
}
QueryTemplateDescriptor has these fields:
| Field | Type | Description |
|---|---|---|
id | string | The template id, such as count or aggregate. AddQueryInput.template takes it. |
resourceType | "database-table" | The kind of resource the template reads. |
title | string | A human-readable title. |
description | string | What the template computes. Optional. |
output | QueryOutputKind | The shape the query's route answers with. |
params | ConfigSchema | The template's parameter schema, in the same vocabulary as the block catalog. |
QueryOutputKind names what the route answers with:
| Kind | Response | Templates |
|---|---|---|
"scalar" | { value }, one number | count, aggregate |
"series" | { series }, one { x, y } point per group | series |
A series point carries its group as x and the measure as y. A bucketed group is a number that sorts, such as 2026, 202601 or 20260114, and not a label. The points are ordered by the group, and a label would need the reader's locale, which the route does not know.
params reads like a block's config schema, described in Catalog. It lists the keys that AddQueryInput.params accepts. A key the template does not declare fails with invalid_config, and so does an unknown template id.
Add a query
import { AddQuery } from "@antelopejs/interface-dms-builder";
const result = await AddQuery("/books", {
name: "inStockCount",
resource: "book",
template: "count",
params: {
where: [{ field: "stock", op: "gt", value: 0 }],
},
});
if (result.ok) {
console.log(result.data.query); // "/books@inStockCount"
console.log(result.data.route); // "/dms/pages/books/stats/in-stock-count"
}
AddQueryInput has these options:
| Option | Type | Description |
|---|---|---|
name | string | The query name, a camelCase identifier. Required. It names the route method, and the model method too. |
resource | ResourceRef | The resource the query reads. Required, and it must exist. |
template | string | A QueryTemplateDescriptor.id. Required. |
params | Record<string, QueryParamValue> | The template's parameters. |
endpoint | string | The route path relative to the page, served at /dms/pages<pageRef><endpoint>. Defaults to /stats/<kebab-name>. |
response | QueryArrangement | How the answer is arranged for the block that reads it. Defaults to what the template computes. |
compare | boolean | Also answer the preceding period, so a card can show a variation. |
The result carries two addresses. query is the QueryRef that configures or removes the query. route is the URL a block fetches from, the endpoint under the page at /dms/pages<pageRef><endpoint>, which pageRoutePath(pageRef, endpoint) from @antelopejs/interface-dms/page also builds. The DMS serves the routes of a page controller under its own /dms/pages prefix, because the page's own path is the page.
The operation enforces these rules:
namemust be a camelCase identifier, or the operation fails withinvalid_config. A name that matches a member of the page or of the model fails withduplicate_namein thequeryscope.endpointmust start with/, or the operation fails withinvalid_config. An endpoint that another route on the page already uses fails withduplicate_name. Any other path is allowed, because read-back identifies a query by its shape and not by its URL.- A model method of that name may already exist and compile a different chain. The builder then emits the model method under a free suffixed name, so the queries that share the original keep their behavior.
Filter the rows
QueryFilter is one condition of a template's where. Filters combine with AND.
| Field | Type | Description |
|---|---|---|
field | string | A field of the resource. It must exist and must not be opaque. |
op | FilterOp | The comparison. |
value | QueryParamValue | A plain scalar written into the chain, or a QueryParamBinding. A scalar must match the field's type. |
FilterOp is "eq" | "ne" | "gt" | "ge" | "lt" | "le". The ordering operators (gt, ge, lt and le) fail with invalid_config on boolean and select fields.
QueryParamValue is a ConfigValue, which is plain data. An ExprValue anywhere in a query's params fails with invalid_config, because a raw expression would put code the builder cannot check inside a model body. Value encodings describes the other sentinels.
import { AddQuery } from "@antelopejs/interface-dms-builder";
await AddQuery("/books", {
name: "revenue",
resource: "book",
template: "aggregate",
params: {
op: "sum",
field: "price",
where: [{ field: "archived", op: "eq", value: false }],
},
});
Bind a value at request time
QueryParamBinding replaces a fixed filter value with a value each request supplies. It becomes a parameter of the model method and a declared @Parameter on the route.
import { AddQuery } from "@antelopejs/interface-dms-builder";
await AddQuery("/books", {
name: "cheaperThan",
resource: "book",
template: "count",
params: {
where: [
{ field: "price", op: "lt", value: { $param: { name: "maxPrice" } } },
],
},
});
// GET /dms/pages/books/stats/cheaper-than?maxPrice=20
| Field | Type | Description |
|---|---|---|
$param.name | string | A camelCase identifier. The route exposes the value under this name. |
$param.in | "query" | "param" | Where the route reads the value from. Defaults to "query". |
name and in describe the route, not the model. The route reads the value from that source, converts it with Number(...), new Date(...) or a comparison with "true" for the field's type, and passes it by position to the model method. The model method names its own parameter from the template.
Two rules apply:
in: "param"reads a path segment, so the endpoint must declare a matching:name. The default/stats/...endpoint has no segment, so a path-bound value needs an endpoint that declares one. A mismatch fails withinvalid_config, and the builder emits no route.- Two filters can bind the same parameter name only when they agree on its type and its source.
import { AddQuery } from "@antelopejs/interface-dms-builder";
await AddQuery("/books", {
name: "countByAuthor",
resource: "book",
template: "count",
endpoint: "/stats/by-author/:authorId",
params: {
where: [
{
field: "authorId",
op: "eq",
value: { $param: { name: "authorId", in: "param" } },
},
],
},
});
Measure per group
The series template answers one point per group instead of one number. A chart, a ranking and the other blocks that show several points read it. A series groups by a field's own value, or by a period of a date field.
import { AddQuery } from "@antelopejs/interface-dms-builder";
await AddQuery("/dashboard", {
name: "monthlyRevenue",
resource: "order",
template: "series",
params: {
op: "sum",
field: "amount",
groupBy: "createdAt",
bucket: "month",
timezone: "Europe/Brussels",
where: [{ field: "status", op: "eq", value: "paid" }],
},
});
// GET /dms/pages/dashboard/stats/monthly-revenue
// { series: [{ x: 202601, y: 1250 }, { x: 202602, y: 980 }] }
| Option | Type | Description |
|---|---|---|
op | "count" | "sum" | "avg" | "min" | "max" | What to measure in each group. Defaults to count. |
field | string | The numeric field the measure reads. Required for every op except count. |
groupBy | string | The field that groups the rows. Required. Without a bucket, it must be a text or numeric field. |
bucket | "day" | "week" | "month" | "quarter" | "year" | Groups a date field by period instead of by exact value. A week runs from Monday to Sunday. Only valid on a date field. |
timezone | string | The IANA zone the period is computed in. |
orderBy | "group" | "measure" | Orders the points by their group, for a timeline, or by the measure, for a ranking. Defaults to group. |
direction | "asc" | "desc" | Defaults to asc. |
limit | number | Keeps only the first N points after ordering, for a top N. A whole number from 1 to 1000. |
where | QueryFilter[] | As for every other template. |
These rules apply to a series:
- A series is always ordered. A database returns groups in its own order, and MongoDB returns them unordered, so the builder always emits an ordering. Without
orderByanddirection, the points come as a timeline, by group, ascending. - Without
timezone, periods are computed in UTC. A row near a period boundary can then fall in a different bucket than in the reader's local time. - A top N is an ordering plus a limit, such as
orderBy: "measure",direction: "desc"andlimit: 5. It has no template of its own.
A week runs from Monday to Sunday, like an ISO week, and a week that straddles New Year stays one week. AddQuery refuses bucket: "week" with invalid_config when the installed @antelopejs/interface-dms cannot name a week for a reader. Bucket by day or month then, or update it.
A series reads back like any other query. GetPageStructure reports its template and the parameters that produced it, including the ordering the engine applies when you omit one. Configuring and removing it work as for a scalar query, and the model method goes with the route.
A chain edited past what the templates accept reads as opaque, as everywhere else. It keeps its endpoint, resource, modelMethod and output. The builder lists and removes it, but never rewrites it.
Arrange the answer
One calculation feeds several kinds of block. response says how the route arranges its answer, so you describe the calculation only once.
| Shape | Answer | Read by |
|---|---|---|
series | { series }, the points | A bare chart |
card | { value?, series, previousValue?, delta?, comparisonSeries? } | A chart card |
value | { value?, previousValue?, delta?, sparkline? } | A KPI card |
items | { items }, the points as ranked entries | A ranked list |
The card, value and items shapes come from the chartCardData, kpiCardData and topListData helpers that @antelopejs/interface-dms/base publishes. The generated route imports them. The route stays one expression, so a query with an arranged answer still reads back as the parameters that produced it.
Two rules apply:
- The headline figure comes from the points. Counts and sums add up, and a min or a max is the min or the max of the group figures. An average is the average of the group averages. When the groups differ in size, that is not the average over all the rows.
compareneeds a period that the route supplies. The route calls the same model method again with thecompareFromandcompareTobounds of the request. The query must bind exactly two date values. A calculation with fixed dates has nothing to shift, so the builder emits no second call.
import { AddQuery } from "@antelopejs/interface-dms-builder";
await AddQuery("/dashboard", {
name: "revenue",
resource: "order",
template: "series",
params: {
op: "sum",
field: "amount",
groupBy: "createdAt",
bucket: "month",
where: [
{ field: "createdAt", op: "ge", value: { $param: { name: "from" } } },
{ field: "createdAt", op: "le", value: { $param: { name: "to" } } },
],
},
response: "card",
compare: true,
});
// GET /dms/pages/dashboard/stats/revenue?from=...&to=...&compareFrom=...&compareTo=...
// { value, series, previousValue, delta, comparisonSeries }
Configure a query
ConfigureQuery(query, patch, opts?) compiles the query again from the merged patch and replaces the route and the model method. A field you leave out keeps the value read back from the file.
import { ConfigureQuery } from "@antelopejs/interface-dms-builder";
await ConfigureQuery("/books@inStockCount", {
params: { where: [{ field: "stock", op: "ge", value: 5 }] },
});
The patch is a Partial<AddQueryInput>. The operation applies its resource, template, params and endpoint. The query keeps the name in its QueryRef, so a name in the patch has no effect. response and compare in the patch also have no effect, and the route the operation writes has neither an arrangement nor a comparison.
A query that no longer reads back as an editable template fails with opaque_target. An opaque chain belongs to a person now, and a chain generated again from a template it no longer matches would undo their edit. To change such a query, remove it and add a new one.
Remove a query
RemoveQuery(query, opts?) deletes the query's route from the page. It deletes the model method too once nothing else calls it, and keeps a method that another query shares. It works on an opaque query as well.
import { RemoveQuery } from "@antelopejs/interface-dms-builder";
await RemoveQuery("/books@cheaperThan");
Read a query back
QueryStructure is a query as found on disk. Read-back is structural. A route reads as a query when its shape and the chain it calls both parse. A hand-written route that matches the grammar is as editable as a generated one, and an edit that keeps the chain inside the grammar reads back again.
| Field | Type | Description |
|---|---|---|
name | string | The query name. Always present. |
endpoint | string | The route path relative to the page's slug, in the form AddQueryInput.endpoint takes. Always present. |
resource | ResourceRef | The resource that the route's model parameter points at. |
modelMethod | string | The model method the route calls. A query looks for a method with its own name or a numbered fork of it, so two queries with different names never share a method, even when their chains match. |
output | QueryOutputKind | The output shape, read from the property the route's response carries. A query whose chain no longer parses still reports what it answers. |
response | QueryArrangement | How the answer is arranged, when the route wraps the calculation in a helper. |
compare | boolean | true when the route also answers the preceding period. |
template | string | The template the chain was compiled from. |
params | Record<string, QueryParamValue> | The parameters that produced the chain. |
routeParams | { name: string; in: "query" | "param" | "header" }[] | The route's declared parameters. They are what a bound value's name and in are read from. header appears only on hand-written routes. |
opaque | boolean | true when the query does not read back as an editable template. |
opaqueReason | "unparseable_route" | "unparseable_chain" | Why the query is opaque. Set when opaque is true. |
Each opaque reason names the half that failed:
unparseable_route. The GET method is not thereturn { value: await model.m(...).run() }shape the builder recognizes.unparseable_chain. The model method it calls is not a chain that any registered template accepts. It was hand-written, edited outside the grammar, or emitted by a newer builder.
A query that no longer parses still reports its endpoint, resource and modelMethod. Only template and params are missing. The builder can always see and remove what it cannot edit.
import { GetPageStructure } from "@antelopejs/interface-dms-builder";
import { pageRoutePath } from "@antelopejs/interface-dms/page";
const result = await GetPageStructure("/books");
if (result.ok) {
const editable = result.data.queries.filter((query) => !query.opaque);
const urls = result.data.queries.map((query) => pageRoutePath("/books", query.endpoint));
}
Next steps
- Value encodings shows how to write configuration values that are not plain literals.