Skip to content

Inside a handler

A handler gets the context of its call as ctx, and the App that declares it as current. The handler of a Mutation or a Query gets both after its input, and a Listener after its Event and its Item. Other pages give the entries of getItem, selectChildren, principalId, sudo, checkRole, publish and the handler of an operation.

ctx.now: DateTime
item.createdAt: Date

The time on the clock of the Runtime, as a Luxon DateTime. A Mutation and a Query read it from ctx. A handler works a time out from it, compares it with a saved datetime, and writes it to one. item.createdAt is the time an Item was created, as a Date.

In the sample timesOf works out the start and the end of a slot on the day of the call.

bookings.ts
const timesOf = (ctx: ReadRuntimeInstance, slot: SlotInput) => {
if (slot.to <= slot.from) throw new Error('A slot ends after it starts');
const day = ctx.now.startOf('day');
const start = day.plus({ hours: slot.from });
return { end: day.plus({ hours: slot.to }), start };
};

Behavior

  • ctx.now is in UTC.
  • In a Mutation ctx.now reads one moment throughout the call, also once the clock has moved on.
  • A Mutation called once the clock has moved on reads the new moment.
  • An Item has as its createdAt the ctx.now of the Mutation that created it.

See: Time, Room bookings that refuse a clash, ReadRuntimeInstance.now.

ctx.getWorkspaceItem(): Promise<ReadWorkspaceItem | undefined>
ctx.getWorkspaceTemplate(): ReadTemplate
ctx.workspaceId: string
app.getWorkspaceTemplate(): TemplateBuilder

Gives the Workspace Item: the one Item of a Workspace that has no parent. In a Mutation it is a WriteWorkspaceItem, and createChild on it creates an Item below it.

Its Template is the Workspace Template, which app.getWorkspaceTemplate() returns to the Builder. An App declares on it the Properties of the Workspace as a whole, with a Role and a Grant for the people who read them. In the sample currency is one.

handlers-app.ts
const setCurrency = app.addMutation('setCurrency', async (input: CurrencyInput, _current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
const updated = await workspace.updateProperties({ currency: input.currency });
return updated.properties.currency;
});

Behavior

  • Every person gets the Workspace Item, and reads on it the Properties that a Grant on the Workspace Template lists for a Role they hold.
  • What a Mutation saves on it, each call after it reads from it.
  • Its id is ctx.workspaceId, and ctx.getWorkspaceTemplate() gives its Template.

See: Workspaces, Define data, ReadRuntimeInstance.getWorkspaceItem.

ctx.apps: Record<string, ReadAppInstance>
ctx.root: ReadAppInstance
current.prn: string

The Apps a handler reaches. ctx.apps holds every App of the Definition by its canonical name: the App of the handler, each App it imports and the built-in App identity. ctx.root is the root App. Each is an App as current is, and prn is its PRN, as prn::shop. In a Mutation each is a WriteAppInstance.

In the sample a Mutation of the App leave finds a person, an Item of the App people that it imports.

leave.ts
if (input.requester !== undefined) {
const requester = await ctx.apps.people.templates.person.getItem(input.requester);
if (requester === undefined) throw new Error('Person not found');
const relation = item.relations.requester;
if (relation.type === 'one') await relation.set(requester);
}

Behavior

  • ctx.apps has each App under the name it gave configure, and none under the key it was imported with.
  • In a handler of an imported App, current is that App, and ctx.root is the root App, which imports it.
  • Through ctx.apps a handler reads an Item of an imported App where a Grant gives it to the person.

See: Root and imported Apps, Compose apps, Tutorial: compose and measure, ReadRuntimeInstance.apps, ReadRuntimeInstance.root.

ctx.hashKey(source: string): Promise<string>

Makes a key from a text that is no key itself, such as an e-mail address or the Identifier that another system gives a customer. The key is sha256: and then the SHA-256 hash of the text, in 64 characters.

Argument Type Description
source string The text, of 1,024 characters at most.

Returns the key. In the sample link makes the key of a customer from an address, so a second call with that address finds the customer of the first.

handlers-app.ts
const link = app.addMutation('link', async (input: LinkInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
const key = await ctx.hashKey(input.email.toLowerCase());
const properties = { name: input.name };
return await workspace.upsertChildByKey(current.templates.customer, { key, properties });
});

Behavior

  • The same text gives the same key in every call, and another text gives another key.
  • An Item takes the key, and getItemByKeyPath finds the Item by it.
  • A text of more than 1,024 characters throws.

See: Hierarchy and keys, ReadRuntimeInstance.hashKey.

current.templates: Record<string, ReadTemplate>
template.prn: string
template.isType(value: unknown): value is ReadItem
ctx.template(prn: string): Promise<ReadTemplate | undefined>

The Templates of an App, by key. A handler passes one to createChild, finds an Item through it with getItem, and selects its Items with selectItems. In a Mutation each is a WriteTemplate.

template.isType tells whether a value is an Item of the Template. ctx.template finds a Template of any App by its PRN, as the sample does with the templatePrn of an Item.

handlers-app.ts
const describe = app.addQuery('describe', async (input: IdInput, current, ctx) => {
const item = await ctx.getItem(input.id);
if (item === undefined) return 'Nothing';
const template = await ctx.template(item.templatePrn);
const isOrder = current.templates.order.isType(item);
return isOrder ? `Order ${item.properties.reference}` : `An Item of ${template?.prn}`;
});

Behavior

  • isType gives true for an Item of the Template, and false for an Item of another Template and for a value that is no Item.
  • template.prn is the templatePrn of each Item of the Template.
  • ctx.template gives undefined for a PRN that names no Template.

See: Hierarchy and keys, Define data, ReadAppInstance.templates.

current.unions: Record<string, ReadUnionInstance>
union.selectItems(): UnionCursorSelector<ReadItem>
union.getItem(id: string): Promise<ReadItem | undefined>
union.isType(value: unknown): value is ReadItem
union.isMember(template: PrnInstance): boolean
union.memberPrns(): string[]

The Unions of an App, by key. A Union selects and finds Items as a Template does, across its Templates. isType tells whether a value is an Item of one of them, isMember whether a Template is one of them, and memberPrns gives the PRN of each. In a Mutation each Item is a WriteItem.

In the sample party is a Union of the Templates customer and supplier.

handlers-app.ts
const parties = app.addQuery('parties', async (input: Partial<IdInput>, current) => {
const party = current.unions.party;
if (input.id !== undefined) {
const found = await party.getItem(input.id);
return party.isType(found) ? [found] : [];
}
const page = await party.selectItems().execute();
return page.results;
});

Behavior

  • selectItems gives the Items of every Template of the Union, and of no other Template.
  • getItem gives undefined for an Item of a Template that is not in the Union.
  • isMember gives true for each Template of the Union, and false for any other.

See: Unions, Relate items, ReadAppInstance.unions.

ctx.selectItems(): ItemCursorSelector<ReadItem>
template.selectItems(): TemplateItemCursorSelector<ReadItem>
selector.template(
template: { prn: string },
): TemplateItemCursorSelector<ReadItem>
selector.union(
template: { prn: string },
): TemplateItemCursorSelector<ReadItem>
selector.prn(
prn: string | string[],
): TemplateItemCursorSelector<ReadItem>

Starts a selector: a selection of Items that further calls narrow, sort and run. template.selectItems selects the Items of one Template, and ctx.selectItems the Items of every Template, until one of the calls below narrows it. In a Mutation each Item a selector gives is a WriteItem.

Modifier What it selects
template The Items of that Template.
union The Items of the Templates of that Union.
prn The Items of the Template or the Union of a PRN, or of a list of PRNs.
tickets.ts
const list = app.addQuery('list', async (_input: unknown, current) => {
const tickets = current.templates.ticket.selectItems();
const page = await tickets.sort(['$createdAt asc']).execute();
return page.results;
});

Behavior

  • template.selectItems gives the Items of the Template in the order they were created, whatever Item each is a child of.
  • ctx.selectItems gives every Item the person gets, of every App, and the Workspace Item.
  • A call on a selector returns a new selector, and the selector it was called on selects what it did before.

See: Data model, Support tickets with an SLA, ReadRuntimeInstance.selectItems.

selector.execute(): Promise<CursorSelectorResult<ReadItem>>
selector.first(): Promise<ReadItem | undefined>
selector.iterator(): AsyncGenerator<ReadItem, void, undefined>
selector.limit(value: number): TemplateItemCursorSelector<ReadItem>
page.results: ReadItem[]
page.cursor: string | undefined

Runs a selection. execute gives one page of it: the Items under results, and under cursor what cursor takes to give the next page. first gives one Item. iterator gives every Item to a for await loop, one page at a time.

Modifier What it sets
limit The number of Items of a page: a whole number of 1 or more.

In the sample the loop runs for each booking of a room that is still booked.

bookings.ts
const stillBooked = bookings.select().state(['booked']);
for await (const other of stillBooked.iterator()) {
const { end: until, start: since } = other.propertyValues;
if (since?.type !== 'datetime' || until?.type !== 'datetime') continue;
if (since.value < end && start < until.value) {
return `${since.value.toFormat('HH:mm')} to ${until.value.toFormat('HH:mm')}`;
}
}

Behavior

  • A page holds 100 Items at most, until limit says another number.
  • iterator gives every Item of the selection, however many pages they fill.
  • first gives undefined where the selection matches no Item.
  • limit throws for a number that is not a whole number of 1 or more.

See: Data model, Room bookings that refuse a clash, TemplateItemCursorSelector.execute, TemplateItemCursorSelector.first, TemplateItemCursorSelector.iterator.

selector.key(
key: string | string[],
): TemplateItemCursorSelector<ReadItem>
selector.state(
state: string | string[],
): TemplateItemCursorSelector<ReadItem>
selector.id(
itemOrItems: SelectorIdInput,
): TemplateItemCursorSelector<ReadItem>
selector.parent(
parentOrParents: SelectorIdInput,
): TemplateItemCursorSelector<ReadItem>

Narrows a selection by what every Item has: a key, a state, an Identifier and a parent. Each call returns a selector, so a handler makes one call after another.

Argument Type Description
key string | string[] A key, or a list of keys.
state string | string[] The key of a state, or a list of them.
Modifier What it keeps
id The Items of an Identifier, or of a list of them. It takes an Item for its Identifier too.
parent The children of an Item, or of a list of Items, each given as id takes it.

In the sample book finds a room by the key it was created with.

bookings.ts
const target = await current.templates.room.selectItems().key(input.room).first();
if (target === undefined) throw new Error('Room not found');
const clash = await findClash(ctx, target, input);

Behavior

  • key keeps the Items that have the key, or one of the keys of a list.
  • state keeps the Items in the state, or in one of the states of a list.
  • A selector with several of these keeps the Items that meet every one.

See: Hierarchy and keys, Room bookings that refuse a clash, TemplateItemCursorSelector.key, TemplateItemCursorSelector.state.

selector.filter(
condition: ItemFilter,
): TemplateItemCursorSelector<ReadItem>

Narrows a selection by the values of Properties and by Relations. A condition is an object: its operator, and what the table lists with it. The selector of a Template or of a Union takes one.

Argument Type Description
condition ItemFilter A condition of the table below.
Operator With Keeps the Items
$equals key, value, caseInsensitive Whose Property key is value: a string, a number or a boolean.
$in key, value Whose Property is one of a list of values.
$includes key, value, caseInsensitive Whose text holds the text value.
$range key, from, to Whose date is on a day from from to to.
$and conditions That meet every condition of a list.
$or conditions That meet one condition of a list, or more.
$exists relationPrn, direction, id That a Relation links to an Item of the list id. direction is 'from' for the Items the Relation is declared on.
$notExists relationPrn, direction, id That it links to none of them.
handlers-app.ts
const rushed = app.addQuery('rushed', async (_input: unknown, current) => {
const orders = current.templates.order.selectItems().filter({
conditions: [
{ key: 'rush', operator: '$equals', value: true },
{ key: 'boxes', operator: '$in', value: [2, 3] },
],
operator: '$and',
});
return (await orders.execute()).results;
});

Behavior

  • Each operator keeps the Items its row says.
  • $equals and $includes tell a capital from a small letter, until caseInsensitive is true.
  • $range keeps the day from, the day to and the days between them.
  • A second filter adds to the first: the selection keeps the Items that meet both.
  • On the selector of ctx.selectItems(), a condition on a Property throws until template narrows it.

See: Data model, Define data, TemplateItemCursorSelector.filter.

selector.sort(condition: ItemSort): TemplateItemCursorSelector<ReadItem>

Orders a selection, by one term or by two. A term is a text, as 'total desc': the key of a Property, then asc or desc. '$createdAt asc' sorts by the time each Item was created, and '$state asc' by the key of its state. A term is also an object, with the options below.

Argument Type Description
condition ItemSort A list of one term or two.
Option Description
key The key of the Property, or createdAt or state with intrinsic.
direction 'ascending' or 'descending'.
caseInsensitive true sorts text without regard to capitals.
nulls 'first' or 'last': where the Items with no value go.
ordinal A list of values, which sort in the order of the list.
intrinsic true for a term on createdAt or on state.
pipeline.ts
const list = app.addQuery('list', async (_input: unknown, current) => {
const deals = current.templates.deal.selectItems();
const page = await deals.sort(['$createdAt asc']).execute();
return page.results;
});

Behavior

  • A term sorts numbers by size, dates by day and text by character, capitals before small letters.
  • An Item with no value comes last in ascending order and first in descending order.
  • The second term orders the Items that the first leaves level.
  • A second sort takes the place of the first.

See: Data model, Sales pipeline with stages, TemplateItemCursorSelector.sort.

selector.join(
...relations: [string, ...string[]],
): TemplateItemCursorSelector<ReadItem>
selector.joinChildren(
child: { prn: string },
options?: { readonly joinType?: 'inner' | 'left' },
): TemplateItemCursorSelector<ReadItem>
selector.joinParents(
parent: { prn: string },
options?: { readonly joinType?: 'inner' | 'left' },
): TemplateItemCursorSelector<ReadItem>

Turns a selection into a selection of other Items: the Items a Relation leads to from the Items selected, their children, or their parents. What narrows the selector before the call chooses the Items to start from. What comes after it narrows and sorts the Items joined to.

Argument Type Description
...relations [string, ...string[]] The key of a Relation of the Template, at either end of it.
child { prn: string } The Template of the children.
options? { readonly joinType?: 'inner' | 'left' } The option below.
parent { prn: string } The Template of the parents.
Option Description
joinType 'inner', which a join with no option uses, gives the Items the selection leads to.

In the sample bought goes from a customer to its open orders, and from those to their lines.

handlers-app.ts
const bought = app.addQuery('bought', async (input: IdInput, current) => {
const buyer = current.templates.customer.selectItems().id(input.id);
const orders = buyer.join('orders').state('open');
const lines = orders.joinChildren(current.templates.line);
return (await lines.execute()).results;
});

Behavior

  • Each call gives the Items it joins to, and a second join starts from the Items of the first.
  • joinChildren gives the children in the order of their parents, where a sort orders the parents.
  • A person gets the Items joined to that a Grant gives them, and none where no Grant gives them one.
  • join throws for a key that is no Relation of the Template.

See: Data model, Relate items, TemplateItemCursorSelector.join, TemplateItemCursorSelector.joinChildren, TemplateItemCursorSelector.joinParents.

selector.paginate(
options: PaginateOptions,
): TemplateItemPaginateSelector<ReadItem>
paged.execute(): Promise<PageSelectorResult<ReadItem>>

Turns a selection into numbered pages. The selector it returns takes key, state, a filter and a sort as before, and its execute gives one page with its counts. An operation returns that page where its output is declared with page.

Argument Type Description
options PaginateOptions The options below.
Option Description
page The number of the page, from 1.
limit The number of Items of a page: a whole number of 1 or more.
Member What it holds
results The Items of the page that the person gets.
page The number of the page.
limit The number of Items of a page.
totalCount The number of Items the selection matches.
pageCount The number of pages they fill.
handlers-app.ts
const pages = app.addQuery('pages', async (input: PageInput, current) => {
const orders = current.templates.order.selectItems().sort(['reference asc']);
return await orders.paginate({ limit: 3, page: input.page }).execute();
});

Behavior

  • A page after the last one holds no Items.
  • A selection that matches no Item fills one page: pageCount is 1.
  • totalCount counts an Item that no Grant gives the person, which results leaves out.

See: Data model, Add queries and mutations, TemplateItemCursorSelector.paginate.

selector.cursor(
value: CursorInput,
): TemplateItemCursorSelector<ReadItem>

Begins a selection after a page that execute gave before. A caller keeps the cursor of that page and sends it back for the next one, as the sample takes it from its input. An operation returns the page where its output is declared with cursor.

Argument Type Description
value CursorInput The cursor of a page, undefined for the first page, or an object with cursor and limit, which sets the number of Items as well.
handlers-app.ts
const browse = app.addQuery('browse', async (input: CursorInput, current) => {
const orders = current.templates.order.selectItems().sort(['total desc']).limit(2);
return await orders.cursor(input.cursor).execute();
});

Behavior

  • With the cursor of a page, the selection gives the Items after that page: in the order they were created, or in the order of a sort by one Property or by two.
  • With undefined, it gives the first page.
  • The page that holds the last Item has no cursor.
  • What narrows the selector holds on every page.

See: Data model, Add queries and mutations, TemplateItemCursorSelector.cursor.

item.archive(): Promise<WriteItem>
item.unarchive(): Promise<WriteItem>
item.isArchived: boolean
selector.archived(
include: boolean | 'include' | 'exclude' | 'only',
): TemplateItemCursorSelector<ReadItem>

Archives an Item: the Item stays saved, and a selector leaves it out. archive and unarchive are calls of a WriteItem, and each returns the Item. isArchived says which it is. archived on a selector says what to do with the archived Items.

Argument Type Description
include boolean | 'include' | 'exclude' | 'only' true or 'include' for the archived Items with the others, 'only' for the archived Items alone, false or 'exclude' to leave them out.

In the sample retire archives an order, and brings an archived one back.

handlers-app.ts
const retire = app.addMutation('retire', async (input: IdInput, current) => {
const item = await current.templates.order.getItem(input.id);
if (item === undefined) throw new Error('Order not found');
return item.isArchived ? await item.unarchive() : await item.archive();
});

Behavior

  • A selector leaves out an archived Item until archived asks for it.
  • getItem finds an archived Item by its Identifier.
  • After unarchive, every selector gives the Item again.

See: Data model, Add queries and mutations, WriteItem.archive, TemplateItemCursorSelector.archived.

ctx.selectEvents(): EventCursorSelector<EventInstance>
events.itemId(id: SelectorIdInput): EventCursorSelector<EventInstance>
events.prn(prn: string | string[]): EventCursorSelector<EventInstance>
events.after(
date: Date | DateTime | number,
): EventCursorSelector<EventInstance>
events.before(
date: Date | DateTime | number,
): EventCursorSelector<EventInstance>

Starts a selector over the Events saved in a Workspace. Only a context of the system has it: a SystemWriteRuntimeInstance, which the sample gets in a script that runs as the system. The selector runs as a selector of Items does, and gives each Event as a Listener gets it.

Modifier What it keeps
itemId The Events published against an Item, or against one of a list.
prn The Events of a PRN, or of one of a list.
after The Events published after a time: a Date, a DateTime or a number of milliseconds.
before The Events published before a time.
run.ts
const history = await workspace.write(async (ctx: SystemWriteRuntimeInstance) => {
const page = await ctx.selectEvents().itemId(dentist.id).execute();
return page.results;
});

Behavior

  • The selector gives the Events in the order they were published.
  • An Event published at the time itself is neither after it nor before it.
  • In a call that runs as a person, selectEvents throws.

See: Events and current state, Tutorial: what happens next, SystemWriteRuntimeInstance.selectEvents.