Resources
The operations that create, read, change and delete a DMS resource, the database table and DataAPI controller behind a feature, and the types they take.
Overview
A resource is the data half of a DMS feature. It is a database Table, a DataController that serves the table over HTTP, and the model that binds them. CreateResource writes all three into a <name>/ folder as database.ts, data-api.ts and an index.ts barrel. It then wires the nearest barrel above that folder, so the project keeps a chain of relative imports up to src/index.ts.
A request describes a resource in semantic terms. Each field carries a DataType and a set of aspects such as searchable or sortable. The engine maps those aspects to the paired decorator stacks on the table and on the controller. A request never names a decorator.
A block that leads with a controller points at a resource. AddBlock with controller: "<ref>" emits the resource's DataAPI class as the block's first argument, as Page operations describes.
Address a resource and a field
ResourceRef is the resource's name in kebab case, such as "product" or "order-line". CreateResource returns it, ListResources reports it, and every other resource operation takes it.
FieldPath addresses one field of a resource as <resourceRef>#<fieldName>, for example product#price. AddField returns the path it created.
import type {
FieldPath,
ResourceRef,
} from "@antelopejs/interface-dms-builder";
const resource: ResourceRef = "product";
const field: FieldPath = "product#price";
Create a resource
CreateResource(input) returns an OpResult<{ ref: ResourceRef; files: ResourceFiles }>.
import { CreateResource } from "@antelopejs/interface-dms-builder";
const result = await CreateResource({
name: "product",
displayName: "Product",
fields: [
{
name: "title",
dataType: { $dataType: "string" },
label: "Title",
required: true,
searchable: true,
sortable: true,
},
{
name: "price",
dataType: { $dataType: "number" },
sortable: true,
filterable: true,
},
],
});
if (result.ok) {
console.log(result.data.ref, result.data.files.dataApi);
}
CreateResourceInput has these options:
| Option | Type | Description |
|---|---|---|
name | string | The resource name. Required. It must contain at least one alphanumeric character, or the operation fails with invalid_config. A name already in use, or a target folder that already exists, fails with duplicate_name. |
fields | FieldSpec[] | The resource's fields. Required. |
displayName | string | A human-readable name for the resource. |
schema | string | The database schema. Defaults to the DMS core schema, CORE_SCHEMA_NAME (dms-core). |
seeds | ConfigObject[] | Rows to seed as a @Fixture. Each row must supply its own _id. |
location | ResourceLocation | The folder the generated <name>/ folder goes in. Omit it for src/<name>/. |
routes | ResourceRoute[] | The DataAPI routes to expose. Omit it for the full set. It must be non-empty when present. |
module | string | The project module to write into, by its id in the project configuration. Unset, the operation writes into the project's own module. The module must be a local module with an src/index.ts, and what the operation writes there can only use declarations from that module. |
The engine derives every generated name from name. For product it writes a Product table class, a ProductModel, a productDataAPI controller on the route /api/product, and a products table.
A location inside a module that mirrors an external database fails with invalid_config, because no table is created there. Map the relations of such a module with MapResources, as External databases describes.
Describe a field
FieldSpec is a FieldAspects plus the field's name. The name never changes. To rename a field, call RemoveField, then AddField.
| Option | Type | Description |
|---|---|---|
name | string | The field name. A name in the catalog's reservedFieldNames fails with invalid_config. |
dataType | DataTypeValue | The field's DataType, for example { $dataType: "string" }. Required. |
label | string | The column header label. Defaults to the field name. |
listable | boolean | The list route selects and lists the field (@Listable). Default true. |
selectable | boolean | The select route offers the field to relation pickers (@Select). |
searchable | boolean | The field is part of full-text search. |
sortable | boolean | The table view can sort by the field. |
filterable | boolean | The table view can filter the field's column. |
access | "read" | "readwrite" | The field's access mode. Default "readwrite". |
required | boolean | Whether the field is required. Default false, which writes @Optional(). |
indexed | boolean | Whether the table indexes the column. When a field is created, the default is true for relation, cascader_relation and tree fields and false for the others. |
order | number | The display order of the column. |
exported | boolean | The resource's CSV export includes the field (@Exported). |
archiveField | boolean | The field is the boolean column that archiving sets (@ArchiveField). |
mandatory | string[] | The routes the field is mandatory on, for example ["new", "edit"] (@Mandatory). |
dbField | { field: string; ts: string; optional?: boolean; decorators?: string[] } | How the table declares the column. It holds the @Field(...) argument, the TypeScript type, and the table decorators the builder does not model, such as @Localized(). The builder keeps the declaration of a field it did not write, instead of narrowing it to the string fallback. |
columnExtras | ConfigObject | The @Column options the builder does not model, such as defaultValue or description. The builder reads them back and writes them again unchanged. |
dataType takes a DataTypeValue sentinel, not a bare string. The ids come from the catalog's dataTypes. See Value encodings and Catalog.
Choose the exposed routes
ResourceRoute names one group of DataAPI endpoints. A subset serves only what the resource needs. A singleton edit form, for example, needs ["get", "edit"] and nothing else. The DataAPI does not register the endpoint of a route you leave out.
| Route | What it exposes |
|---|---|
list | The paginated listing (list, count, countBatch and summary). |
get | Read a single row. |
create | Create a row (new). |
edit | Update a row. |
delete | Delete a row. |
select | Option lists for the relation pickers that reference this resource. |
archive | Soft delete and undo (archive and restore). |
export | The export endpoints (exportStart, exportStatus and exportDownload). |
import { CreateResource } from "@antelopejs/interface-dms-builder";
await CreateResource({
name: "site-settings",
fields: [{ name: "title", dataType: { $dataType: "string" } }],
routes: ["get", "edit"],
});
An empty array, or a name that is not one of the eight, fails with invalid_config.
ConfigureResource(ref, patch, opts?) changes the routes of an existing resource. patch.routes replaces the current set, so pass the whole list. A patch without routes changes nothing. An empty array fails with invalid_config. A controller with no route map to patch fails with unsupported.
import { ConfigureResource } from "@antelopejs/interface-dms-builder";
await ConfigureResource("site-settings", { routes: ["get", "edit", "list"] });
Place the generated files
ResourceLocation sets the folder that the <name>/ folder goes in. The engine wires the barrel nearest to that folder, and falls back to the root barrel.
| Form | Where the resource goes |
|---|---|
| Omitted | src/<name>/. |
"reporting/data" | src/reporting/data/<name>/. The string is a folder relative to the src root and must stay inside the src tree. |
{ category: "pages.reports" } | The source folder of that category, as for a page. A root category falls back to the src root. |
{ page: "/revenue" } | Inside that page's feature folder, so the page imports ./<name>/data-api. |
import { CreateResource } from "@antelopejs/interface-dms-builder";
await CreateResource({
name: "revenue-entry",
fields: [{ name: "amount", dataType: { $dataType: "number" } }],
location: { page: "/revenue" },
});
A string that leaves the src tree, an unknown category and an unknown page each fail with invalid_config.
Add, configure and remove a field
AddField(ref, field, opts?) adds a field to both generated files and returns its FieldPath.
import { AddField } from "@antelopejs/interface-dms-builder";
const result = await AddField("product", {
name: "sku",
dataType: { $dataType: "string" },
label: "SKU",
indexed: true,
searchable: true,
});
if (result.ok) {
console.log(result.data.path); // "product#sku"
}
A name that the table or the controller already declares fails with duplicate_name. A reserved name fails with invalid_config. So does a resource that mirrors an external database, whose columns belong to that database.
ConfigureField(path, patch, opts?) reads the field's current aspects, merges your Partial<FieldAspects> over them, and writes the field again from the result. An aspect you leave out keeps its current value. The operation rewrites the table file only when the patch sets dataType or indexed.
import { ConfigureField } from "@antelopejs/interface-dms-builder";
await ConfigureField("product#price", {
filterable: true,
order: 2,
});
A field whose decorator stack the builder cannot read back is opaque. A hand-edited field and a field with a decorator the builder does not know are two examples. Configuring an opaque field fails with opaque_target.
RemoveField(path, opts?) removes the field from both files.
import { RemoveField } from "@antelopejs/interface-dms-builder";
await RemoveField("product#sku");
All three take a MutationOpts. Its expectedVersion is compared with the resource's version, a hash of both generated files, and a mismatch fails with stale. A path whose resource or field does not exist fails with not_found.
List resources
ListResources() returns a ResourceSummary[] directly, without an OpResult around it.
| Field | Type | Description |
|---|---|---|
ref | ResourceRef | The resource's ref. |
className | string | The generated table class name. |
tableName | string | The database table name. |
route | string | The DataAPI's base route. |
fieldCount | number | The number of fields the resource has. |
files | { database: string; dataApi: string } | The two source files. |
sourceModule | string | The project module the resource lives in. Present only when that module is not the project's own. |
import { ListResources } from "@antelopejs/interface-dms-builder";
const resources = await ListResources();
const refs = resources.map((resource) => resource.ref);
Read a resource's structure
GetResourceStructure(ref) returns an OpResult<ResourceStructure>. Like the other reads, it returns an empty changes array. An unknown ref fails with not_found.
import { GetResourceStructure } from "@antelopejs/interface-dms-builder";
const result = await GetResourceStructure("product");
if (result.ok) {
const editable = result.data.fields.filter((field) => !field.opaque);
}
ResourceStructure has these fields:
| Field | Type | Description |
|---|---|---|
ref | ResourceRef | The resource's ref. |
className | string | The generated table class name. |
tableName | string | The database table name. |
route | string | The DataAPI's base route. |
schema | string | The database schema the table is registered in. |
files | ResourceFiles | The resource's three files. |
fields | ResourceFieldStructure[] | The fields, in declaration order. The _id and model members every resource has are left out. |
routes | ResourceRoute[] | The exposed routes when the resource serves a subset. Absent when it serves the full set. Also absent for a hand-edited route map that the engine cannot map back to route names. |
version | string | A content hash of both generated files. |
ResourceFiles holds the paths of a resource's three files, as database, dataApi and index.
ResourceFieldStructure is a Partial<FieldAspects> plus these fields:
| Field | Type | Description |
|---|---|---|
name | string | The field name. Always present. |
opaque | boolean | true when the builder cannot read the field's decorator stack back. |
opaqueReason | string | Why the field is opaque, such as an unsupported decorator or a missing @Column stack. Set when opaque is true. |
A field the builder reads back carries its aspects. An opaque field carries only name, opaque and opaqueReason. Check opaque before you offer a field for editing.
Delete a resource
DeleteResource(ref, opts?) deletes the three generated files and removes every import of the resource. It then removes the folder if the folder is empty. By default it also deletes every row of the resource's table, so a later resource with the same name seeds again from an empty table.
import { DeleteResource } from "@antelopejs/interface-dms-builder";
const result = await DeleteResource("product");
if (result.ok) {
for (const warning of result.warnings ?? []) {
console.log(warning.code, warning.message);
}
}
DeleteResourceOpts extends MutationOpts:
| Option | Type | Description |
|---|---|---|
keepData | boolean | Leave the rows of the resource's table in place. |
expectedVersion | string | The ResourceStructure.version you last read. A mismatch fails with stale. |
While another resource imports this one, through a relation field for example, the operation fails with referential_integrity. The error's blockedBy lists those resources.
When the rows cannot be deleted, the operation still succeeds and adds a data_not_dropped warning with the reason. The files are gone and the rows may remain. A resource that mirrors an external database keeps its rows, and the operation adds a data_kept warning.
import { DeleteResource } from "@antelopejs/interface-dms-builder";
await DeleteResource("product", { keepData: true });
Next steps
- Queries shows how to derive counts and aggregates from a resource and serve them from a page.