Skip to content

Templates, Properties, Relations

A Template declares a kind of Item: the Properties an Item holds and the Relations between it and other Items. A handler creates Items, finds them, reads and writes their Properties, and follows a Relation from either side.

app.addTemplate(key: string): TemplateBuilder

Declares a Template: a kind of Item that the App saves. Every Item is an Item of one Template, and holds the Properties, the Relations and the states that the Template declares.

Argument Type Description
key string A lowercase letter, then letters and digits, 64 characters at most. An App uses a Template key once. The keys workspace and root are reserved.

Returns the Template, which the calls below declare Properties and Relations on. A handler reaches the Template under its key, as current.templates.leaveRequest here.

leave.ts
const leaveRequest = app.addTemplate('leaveRequest');
leaveRequest.addProperty('reason', 'string');
leaveRequest.addProperty('days', 'integer');

Behavior

  • A handler finds an Item through its Template, and through no other: getItem on another Template gives undefined for it.
  • An Item saves a value for a Property its Template declares, and for no other key.

See: Data model, Define data, Tutorial: the lifecycle, AppBuilder.addTemplate.

template.addProperty(
key: string,
type: PropertyDefinitionType | ZodType,
options?: PropertyDefinitionOptions,
): PropertyBuilder
property.index(): TemplatePropertyBuilder
property.setLabel(label: string): TemplatePropertyBuilder
select.addOption(
key: string,
input: AddOptionInput,
): TemplateSelectPropertyBuilder

Declares a Property: a value of one data type, under a key, that every Item of the Template can hold.

Argument Type Description
key string A key as for a Template. A Template uses a Property key once. The keys id, state and root are reserved.
type PropertyDefinitionType | ZodType A data type of the table below, by its name. For json, a Zod type in place of the name.
options? PropertyDefinitionOptions The options of the second table.
Data type Holds A handler writes and reads
string Text. string
integer A whole number. number
number A number, whole or not. number
boolean True or false. boolean
id An Identifier, as of an Item or of a principal. string, saved in lower case
date A day of the calendar. string, as '2020-02-03'
duration A length of time in ISO 8601. string, as 'PT90M'
datetime A moment in a time zone. A Luxon DateTime, as ctx.now is, in the time zone it was written in
instant A moment. A Luxon DateTime, read back in UTC
single-select One option of the Property. string, the key of the option
multi-select Any number of the options of the Property. string[], the keys of the options
json A value the Zod type accepts. That value
Option Description
label The label of the Property. Without it, the label is the key.
format What the value is, within its data type. For a string: 'content', 'email', 'hex-color' or 'url'. For an integer: 'likert', 'month' or 'year'. For a select: 'country-code' or 'time-zone', which stands in place of its options.

Returns the Property, with the modifiers its data type has. Each returns the Property, so they chain.

Modifier What it declares
index An index on the Property. A Property takes one index.
setLabel The label of the Property, as the option label does.
addOption On a select, an option. Its key is the value a handler writes. Its input is {}, or holds the label of the option.
data-app.ts
course.addProperty('title', 'string', { label: 'Title' }).index();
course.addProperty('opensAt', 'datetime');
const level = course.addProperty('level', 'single-select');
level.addOption('beginner', { label: 'Beginner' });
level.addOption('advanced', { label: 'Advanced' });
const topics = course.addProperty('topics', 'multi-select');
topics.addOption('design', {});
topics.addOption('code', {});
course.addProperty('venue', z.object({ city: z.string(), room: z.string() }));

Behavior

  • A handler reads back the value it wrote, in the form the table gives for the data type.
  • An id is saved in lower case. A datetime keeps the time zone it was written in, and an instant reads back in UTC.
  • A Property with no value reads undefined, for every data type but a select.
  • A select declared with the format 'time-zone' takes the name of a time zone, as 'Europe/Lisbon'.

See: Properties and incomplete data, Define data, Room bookings that refuse a clash, TemplateBuilder.addProperty.

template.addRelation(
key: string,
cardinality: RelationCardinality,
to: TemplateBuilder | UnionBuilder,
options?: RelationOptions,
): RelationBuilder

Declares a Relation from the Items of the Template to the Items of another Template, or of the same one. An Item on either side reads the Relation, each side under a key of its own.

Argument Type Description
key string The key of the Relation on an Item of the Template. A key as for a Template. A Template uses a Relation key once.
cardinality RelationCardinality How many Items each side reads, from the table below.
to TemplateBuilder | UnionBuilder The Template the Relation leads to, or a Union of Templates.
options? RelationOptions The option of the second table.
Cardinality An Item of the Template reads An Item of to reads
many-to-one One Item Many Items
one-to-many Many Items One Item
many-to-many Many Items Many Items
Option Description
toKey The key of the Relation on an Item of to. Without it, that key is key. A Template uses a toKey once among the Relations that lead to it, and a Relation from a Template to itself takes a toKey that is not its key.

Returns the Relation.

data-app.ts
course.addRelation('teacher', 'many-to-one', person, { toKey: 'teaches' });
course.addRelation('students', 'many-to-many', person, { toKey: 'attends' });
person.addRelation('mentees', 'one-to-many', person, { toKey: 'mentor' });

Behavior

  • many-to-one: a course sets its one teacher, and that person reads every course under teaches.
  • one-to-many: a person adds mentees, and each of them reads that person as its one mentor.
  • many-to-many: a course adds students, a person adds courses under attends, and each side reads what the other added.

See: Relations, Relate items, Sales pipeline with stages, TemplateBuilder.addRelation.

app.addUnion(key: string, templates: TemplateBuilder[]): UnionBuilder

Declares a Union: a group of Templates under one key. A Relation that leads to a Union takes an Item of any Template of the group, so one Relation reaches Items of several kinds.

Argument Type Description
key string A key as for a Template. An App uses a Union key once.
templates TemplateBuilder[] The Templates of the group.

Returns the Union, which addRelation takes as to. A Union declares no Property: each Template of the group keeps its own. In the sample a lesson has one place, which is a room or a hall, and a room and a hall each read their lessons.

data-app.ts
const hall = app.addTemplate('hall');
hall.addProperty('name', 'string');
const place = app.addUnion('place', [room, hall]);
const lesson = app.addTemplate('lesson');
lesson.addProperty('title', 'string');
lesson.addRelation('place', 'many-to-one', place, { toKey: 'lessons' });

Behavior

  • A Relation that leads to a Union takes an Item of each Template of the group, and each of those Items reads the Relation back under the toKey.
  • set and add throw on an Item of a Template that is not in the group.

See: Unions, Relate items, AppBuilder.addUnion.

item.properties: PropertyMap
item.propertyValues: PropertyValueMap

The Properties of an Item, each under its key, in two forms. properties holds the value alone, as item.properties.title. propertyValues holds an object: the value as value, and the name of its data type as type.

TypeScript gives a value of properties no type. In propertyValues, a test of type gives value its type: in the sample, dueAt.value is a DateTime once dueAt?.type !== 'datetime' is ruled out. Read propertyValues where a handler needs that type, and properties elsewhere.

tickets.ts
slaCheck.addListener('markOverdue', async (_event, item, _current, ctx) => {
const dueAt = item.propertyValues.dueAt;
const breach = item.state?.transitions.breach;
if (dueAt?.type !== 'datetime' || breach === undefined) return;
if (dueAt.value <= ctx.now) await breach.execute({});
});

Behavior

  • A select is the key of its option in properties, and the option, with its key and label, in propertyValues.
  • A datetime from propertyValues compares with ctx.now, as in the sample.

See: Properties and incomplete data, Handle incomplete data, Support tickets with an SLA, ReadItem.properties, ReadItem.propertyValues.

item.createChild(
template: BaseReadTemplate,
options: CreateChildOptions,
): Promise<WriteItem>
template.createItem(
parent: BaseWriteItem,
options: CreateChildOptions,
): Promise<WriteItem>
item.key: string | undefined
item.parentId: string | undefined

Creates an Item of a Template as a child of the Item the call is made on. An Item with no other parent is a child of the Workspace Item, which ctx.getWorkspaceItem() gives.

Argument Type Description
template BaseReadTemplate The Template of the new Item, as current.templates.ticket.
options CreateChildOptions The options below. Pass {} for none.
Option Description
properties The values of the new Item, each under the key of its Property.
key A key for the new Item among the children of its parent. getItemByKeyPath finds the Item by it.

Returns the new Item. Its parentId is the Identifier of its parent, and its key is the key it was given or undefined. template.createItem does the same, with the parent as its first argument.

tickets.ts
const general = await ctx.getItemByKeyPath('general');
if (general === undefined) throw new Error('Queue not found');
return await general.createChild(current.templates.ticket, {
properties: {
dueAt: ctx.now.plus({ hours: 4 }),
openedBy: ctx.principalId,
subject: input.subject,
},
});

Behavior

  • The new Item is a child of the Item it is created on, with either call.
  • Creating a child with a key that a sibling holds moves the key to the new child. The sibling keeps its Identifier and loses its key.
  • The call does not throw on a value of the wrong kind for its Property. That Property reads back undefined, for every data type but a select.

See: Hierarchy and keys, Define data, Support tickets with an SLA, WriteItem.createChild.

item.updateProperties(
input: Record<string, unknown>,
): Promise<WriteItem>

Saves new values for some of the Properties of an Item, in a Mutation or a Listener.

Argument Type Description
input Record<string, unknown> The new values, each under the key of its Property.

Returns the Item with the new values. The call does not change the Item it is made on, so a handler carries on with the Item it gets back. The sample reads the transition from updated, not from parent.

onboarding.ts
checklist.addParentListener('countDone', finished, async (_event, parent) => {
const { done, total } = parent.properties;
if (typeof done !== 'number') return;
const updated = await parent.updateProperties({ done: done + 1 });
const transition = updated.state?.transitions.complete;
if (done + 1 === total) await transition?.execute({});
});

Behavior

  • The Item it returns reads the new values, and the Item the call was made on reads the old ones. A Property that input does not name keeps its value.
  • A single-select given null reads null: no option is chosen.

See: Properties and incomplete data, Handle incomplete data, Roll a number up to a parent, WriteItem.updateProperties.

item.upsertChildByKey(
template: BaseReadTemplate,
options: UpsertChildByKeyOptions,
): Promise<WriteItem>

Creates the child of an Item that has a key, or writes to the child that has that key already. Use it where a call can come twice for one thing: in the sample a person who joins twice is still one rep.

Argument Type Description
template BaseReadTemplate The Template of the child.
options UpsertChildByKeyOptions The options below.
Option Description
key The key of the child.
properties The values to save, as for createChild.
onConflict What the call does with a child that has the key. 'merge' writes properties to it, and 'ignore' leaves it as it is. Without it, the call does as with 'merge'.

Returns the child that has the key.

pipeline.ts
const join = app.addMutation('join', async (input: NameInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
return await workspace.upsertChildByKey(current.templates.rep, {
key: ctx.principalId,
onConflict: 'merge',
properties: { name: input.name },
});
});

Behavior

  • One child of the Item has the key, however many calls name it.
  • With 'merge', and with no onConflict, a later call writes its properties to that child. With 'ignore', the child keeps its values.
  • A call with no key throws.

See: Hierarchy and keys, Define data, Sales pipeline with stages, WriteItem.upsertChildByKey.

ctx.getItem(id: string): Promise<ReadItem | undefined>
ctx.getItemByKeyPath(
...parts: [string, ...string[]],
): Promise<ReadItem | undefined>
template.getItem(id: string): Promise<ReadItem | undefined>
template.selectItems(): TemplateItemCursorSelector<ReadItem>

Finds an Item by its Identifier, or by the keys that lead to it from the Workspace Item. In a Mutation each call gives a WriteItem.

Argument Type Description
id string The Identifier of the Item.
...parts [string, ...string[]] One key or more. The first is the key of a child of the Workspace Item, and each one after it is the key of a child of the Item before.

ctx.getItem finds an Item of any Template, and template.getItem an Item of that Template alone. template.selectItems() returns a selector over the Items of the Template: its execute() gives a page of them under results.

data-app.ts
const parent = await ctx.getItemByKeyPath(input.code);
const where = await ctx.getItem(input.place);
if (parent === undefined || where === undefined) throw new Error('Course or place not found');

Behavior

  • template.getItem gives undefined for an Item of another Template.
  • getItemByKeyPath gives undefined where a key matches no child.
  • Each call gives undefined for an Item that no Grant on its Template shows to the principal.

See: Hierarchy and keys, Define data, Sales pipeline with stages, ReadRuntimeInstance.getItem, ReadRuntimeInstance.getItemByKeyPath.

item.getParent(): Promise<ReadItem | undefined>
item.selectChildren(): ItemCursorSelector<ReadItem>

The Item above an Item, and the Items below it. getParent gives the Item that createChild was called on to create this one. selectChildren returns a selector over the children of the Item: its execute() gives a page of them under results. In a Mutation each Item they give is a WriteItem.

In the sample a lesson is a child of its course: siblings goes up from one lesson to the course, then down to every lesson of that course.

data-app.ts
const siblings = app.addQuery('siblings', async (input: IdInput, current) => {
const item = await current.templates.lesson.getItem(input.id);
const parent = await item?.getParent();
if (parent === undefined) throw new Error('Lesson not found');
const page = await parent.selectChildren().execute();
return page.results;
});

Behavior

  • getParent gives the Workspace Item for an Item that was created on it.
  • selectChildren gives the children of that Item alone, in the order they were created.

See: Hierarchy and keys, Define data, Support tickets with an SLA, ReadItem.getParent, ReadItem.selectChildren.

item.relations: Record<string, ReadRelationInstance>
relation.type: 'one'
relation.get(): Promise<RelatedItem<ReadItem> | undefined>
relation.set(target: WriteItem): Promise<boolean>
relation.clear(): Promise<boolean>

The side of a Relation that reads one Item. item.relations holds each Relation of an Item under its key, and the type of this side is 'one'. A handler tests that before it calls get, set or clear, as the sample does. A Mutation has set and clear.

Argument Type Description
target WriteItem The Item the Relation is to lead to.

get returns the Item the Relation leads to. set and clear return true or false.

pipeline.ts
const item = await workspace.createChild(current.templates.deal, {
properties: { movedAt: ctx.now, name: input.name },
});
const relation = item.relations.rep;
if (relation.type === 'one') await relation.set(owner);
return item;

Behavior

  • get gives undefined until set is called, and again after clear.
  • set gives true when no target was set before, and false for the Item that is the target already. A new target takes the place of the old one, which no longer reads the Item.
  • clear gives true when it takes a target away, false when there is none.
  • set throws on an Item of a Template the Relation does not lead to.

See: Relations, Relate items, Sales pipeline with stages, ReadOneRelationInstance.get, WriteOneRelationInstance.set, WriteOneRelationInstance.clear.

relation.type: 'many'
relation.select(
options?: RelationSelectOptions,
): TemplateItemCursorSelector<RelatedItem<ReadItem>>
relation.add(target: WriteItem): Promise<boolean>
relation.add(targets: WriteItem[]): Promise<boolean[]>
relation.remove(target: WriteItem): Promise<boolean>
relation.remove(targets: WriteItem[]): Promise<boolean[]>
relation.clear(): Promise<void>

The side of a Relation that reads many Items: its type is 'many'. select returns a selector over the Items the Relation leads to. add and remove take one Item or a list, and clear takes every target away. Those three are there in a Mutation.

Argument Type Description
options? RelationSelectOptions Whether to include targets whose Relation has been removed. { removed: 'include' } includes them; the default leaves them out.
target WriteItem The Item to add or to remove.
targets WriteItem[] A list of Items. The call returns one answer for each, in the order of the list.

add and remove return whether the call changed anything.

data-app.ts
const enroll = app.addMutation('enroll', async (input: PersonInput, current, ctx) => {
const item = await ctx.getItemByKeyPath(input.code);
const student = await current.templates.person.getItem(input.person);
const relation = item?.relations.students;
if (student === undefined || relation?.type !== 'many') throw new Error('Course or person not found');
await relation.add(student);
const page = await relation.select().execute();
return page.results;
});

Behavior

  • add gives true for a new target and false for an Item that is a target already. remove gives true for a target and false for any other Item.
  • Either side of a many-to-many Relation adds and removes, and the other side reads the result.
  • Where the other side reads one Item, add gives false for an Item that has its one already, and changes nothing. set from that Item moves it.
  • select reads every target, however many there are.

See: Relations, Relate items, Room bookings that refuse a clash, ReadManyRelationInstance.select, WriteManyRelationInstance.add, WriteManyRelationInstance.remove.