[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationResources

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.

typescript
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 }>.

typescript
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:

OptionTypeDescription
namestringThe 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.
fieldsFieldSpec[]The resource's fields. Required.
displayNamestringA human-readable name for the resource.
schemastringThe database schema. Defaults to the DMS core schema, CORE_SCHEMA_NAME (dms-core).
seedsConfigObject[]Rows to seed as a @Fixture. Each row must supply its own _id.
locationResourceLocationThe folder the generated <name>/ folder goes in. Omit it for src/<name>/.
routesResourceRoute[]The DataAPI routes to expose. Omit it for the full set. It must be non-empty when present.
modulestringThe 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.

OptionTypeDescription
namestringThe field name. A name in the catalog's reservedFieldNames fails with invalid_config.
dataTypeDataTypeValueThe field's DataType, for example { $dataType: "string" }. Required.
labelstringThe column header label. Defaults to the field name.
listablebooleanThe list route selects and lists the field (@Listable). Default true.
selectablebooleanThe select route offers the field to relation pickers (@Select).
searchablebooleanThe field is part of full-text search.
sortablebooleanThe table view can sort by the field.
filterablebooleanThe table view can filter the field's column.
access"read" | "readwrite"The field's access mode. Default "readwrite".
requiredbooleanWhether the field is required. Default false, which writes @Optional().
indexedbooleanWhether 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.
ordernumberThe display order of the column.
exportedbooleanThe resource's CSV export includes the field (@Exported).
archiveFieldbooleanThe field is the boolean column that archiving sets (@ArchiveField).
mandatorystring[]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.
columnExtrasConfigObjectThe @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.

RouteWhat it exposes
listThe paginated listing (list, count, countBatch and summary).
getRead a single row.
createCreate a row (new).
editUpdate a row.
deleteDelete a row.
selectOption lists for the relation pickers that reference this resource.
archiveSoft delete and undo (archive and restore).
exportThe export endpoints (exportStart, exportStatus and exportDownload).
typescript
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.

typescript
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.

FormWhere the resource goes
Omittedsrc/<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.
typescript
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.

typescript
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.

typescript
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.

typescript
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.

FieldTypeDescription
refResourceRefThe resource's ref.
classNamestringThe generated table class name.
tableNamestringThe database table name.
routestringThe DataAPI's base route.
fieldCountnumberThe number of fields the resource has.
files{ database: string; dataApi: string }The two source files.
sourceModulestringThe project module the resource lives in. Present only when that module is not the project's own.
typescript
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.

typescript
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:

FieldTypeDescription
refResourceRefThe resource's ref.
classNamestringThe generated table class name.
tableNamestringThe database table name.
routestringThe DataAPI's base route.
schemastringThe database schema the table is registered in.
filesResourceFilesThe resource's three files.
fieldsResourceFieldStructure[]The fields, in declaration order. The _id and model members every resource has are left out.
routesResourceRoute[]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.
versionstringA 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:

FieldTypeDescription
namestringThe field name. Always present.
opaquebooleantrue when the builder cannot read the field's decorator stack back.
opaqueReasonstringWhy 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.

typescript
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:

OptionTypeDescription
keepDatabooleanLeave the rows of the resource's table in place.
expectedVersionstringThe 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.

typescript
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.