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.
Builder calls
Section titled “Builder calls”addTemplate
Section titled “addTemplate”app.addTemplate(key: string): TemplateBuilderDeclares 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.
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:
getItemon another Template givesundefinedfor 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.
addProperty
Section titled “addProperty”template.addProperty( key: string, type: PropertyDefinitionType | ZodType, options?: PropertyDefinitionOptions,): PropertyBuilderproperty.index(): TemplatePropertyBuilderproperty.setLabel(label: string): TemplatePropertyBuilderselect.addOption( key: string, input: AddOptionInput,): TemplateSelectPropertyBuilderDeclares 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. |
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
idis saved in lower case. Adatetimekeeps the time zone it was written in, and aninstantreads 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.
addRelation
Section titled “addRelation”template.addRelation( key: string, cardinality: RelationCardinality, to: TemplateBuilder | UnionBuilder, options?: RelationOptions,): RelationBuilderDeclares 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.
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 oneteacher, and that person reads every course underteaches.one-to-many: a person addsmentees, and each of them reads that person as its onementor.many-to-many: a course addsstudents, a person adds courses underattends, and each side reads what the other added.
See: Relations, Relate items, Sales pipeline with stages, TemplateBuilder.addRelation.
addUnion
Section titled “addUnion”app.addUnion(key: string, templates: TemplateBuilder[]): UnionBuilderDeclares 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.
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. setandaddthrow on an Item of a Template that is not in the group.
See: Unions, Relate items, AppBuilder.addUnion.
In a handler
Section titled “In a handler”properties, propertyValues
Section titled “properties, propertyValues”item.properties: PropertyMapitem.propertyValues: PropertyValueMapThe 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.
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 itskeyandlabel, inpropertyValues. - A
datetimefrompropertyValuescompares withctx.now, as in the sample.
See: Properties and incomplete data, Handle incomplete data, Support tickets with an SLA, ReadItem.properties, ReadItem.propertyValues.
createChild
Section titled “createChild”item.createChild( template: BaseReadTemplate, options: CreateChildOptions,): Promise<WriteItem>template.createItem( parent: BaseWriteItem, options: CreateChildOptions,): Promise<WriteItem>item.key: string | undefineditem.parentId: string | undefinedCreates 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.
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.
updateProperties
Section titled “updateProperties”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.
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
inputdoes not name keeps its value. - A
single-selectgivennullreadsnull: no option is chosen.
See: Properties and incomplete data, Handle incomplete data, Roll a number up to a parent, WriteItem.updateProperties.
upsertChildByKey
Section titled “upsertChildByKey”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.
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 noonConflict, a later call writes itspropertiesto that child. With'ignore', the child keeps its values. - A call with no
keythrows.
See: Hierarchy and keys, Define data, Sales pipeline with stages, WriteItem.upsertChildByKey.
getItem, getItemByKeyPath
Section titled “getItem, getItemByKeyPath”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.
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.getItemgivesundefinedfor an Item of another Template.getItemByKeyPathgivesundefinedwhere a key matches no child.- Each call gives
undefinedfor 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.
getParent, selectChildren
Section titled “getParent, selectChildren”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.
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
getParentgives the Workspace Item for an Item that was created on it.selectChildrengives 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.
get, set, clear
Section titled “get, set, clear”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.
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
getgivesundefineduntilsetis called, and again afterclear.setgivestruewhen no target was set before, andfalsefor the Item that is the target already. A new target takes the place of the old one, which no longer reads the Item.cleargivestruewhen it takes a target away,falsewhen there is none.setthrows 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.
select, add, remove
Section titled “select, add, remove”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.
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
addgivestruefor a new target andfalsefor an Item that is a target already.removegivestruefor a target andfalsefor any other Item.- Either side of a
many-to-manyRelation adds and removes, and the other side reads the result. - Where the other side reads one Item,
addgivesfalsefor an Item that has its one already, and changes nothing.setfrom that Item moves it. selectreads every target, however many there are.
See: Relations, Relate items, Room bookings that refuse a clash, ReadManyRelationInstance.select, WriteManyRelationInstance.add, WriteManyRelationInstance.remove.

