Tutorial: compose and measure
Chapter 3 ended with an App that acts after every decision. It still works alone, and nothing adds up what it has done. In this chapter the leave App imports a second App that holds people, each request points at the person who asked for it, and a Metric counts the approvals.
What you build
Section titled “What you build”| You add | What it gives you |
|---|---|
A people App, imported by the leave App |
person Items that a leave request can point at |
A requester Relation |
The person who asked, one step from the request |
An approvals Metric with a requester Dimension |
The number of approvals, in total and for each person |
One imported App, one Relation and one Metric with a Dimension.
Before you start
Section titled “Before you start”You need leave.ts and run.ts from chapter 3, with all five steps done. This chapter uses one package the Quickstart did not install. Install it:
npm install @pyn-backend/platform-projector-sqliteYou run the App the same way in every step:
PYN_ENV=local npx tsx run.tsIt prints:
Leave App is running in Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Requested: "Summer holiday" is pendingApproved: "Summer holiday" is approvedListener: "Summer holiday" is approvedRejected: "Moving house" is rejectedCanceled: "Summer holiday" is canceledListed: "Summer holiday" is canceledListed: "Moving house" is rejectedRefused: A rejected leave request cannot be canceledListed: "Summer holiday" is canceledListed: "Moving house" is rejectedJoined: Alice holds prn::leave:role/employeeJoined: Bob holds prn::leave:role/managerAs Alice: "Long weekend" is pendingAs Alice: Refused. Grant assertion failed for the current principal: none of [prn::leave:role/manager] heldAs Bob: "Long weekend" is approvedListener: "Long weekend" is approvedAs Bob: "Dentist" is rejectedEvent: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}As Alice: "Dentist" has no noticeAs Alice: "Dentist" has the notice "Rejected: Team offsite"As Alice: "Wedding" is pendingClock: Wed, 01 Jan 2020 00:00:00 GMTAs Alice: "Wedding" has no noticeClock: Thu, 02 Jan 2020 00:00:00 GMTAs Alice: "Wedding" has the notice "Waiting for a decision"As Alice: "Dentist" has the notice "Rejected: Team offsite"Every step below adds lines after these, and shows only the lines it adds.
1. Import an App that holds people
Section titled “1. Import an App that holds people”An App can import another App and use what it declares. Next to leave.ts, create people.ts. It is a second App, with one Template:
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
export const peopleApp: AppSpec = (app) => { app.configure('people');
const person = app.addTemplate('person'); person.addProperty('name', 'string');};In leave.ts, import the file below the first line:
import { peopleApp } from './people';Then import the App, below app.configure('leave');:
const people = app.addDependency('people', peopleApp); const person = people.templates.person;addDependency adds the people App to yours and returns a handle on it. people.templates.person is its person Template. You use it in leave.ts like a Template of your own.
At the end of run.ts, above the last line, add Alice and Bob to the people App:
// Add Alice and Bob to the people App.const persons = await workspace.write(async (ctx) => { const root = await ctx.getWorkspaceItem(); const person = ctx.apps.people.templates.person; const alice = await person.createItem(root, { properties: { name: 'Alice' } }); const bob = await person.createItem(root, { properties: { name: 'Bob' } }); return { alice: alice.id, bob: bob.id };});for (const id of [persons.alice, persons.bob]) { const item = await workspace.read(async (ctx) => await ctx.getItem(id)); console.log(`Person: ${item?.properties.name} is an Item of ${item?.templatePrn}`);}Your script reaches the imported App by its name, ctx.apps.people, the same way it reaches ctx.apps.leave.
Run it. You should see two new lines:
Person: Alice is an Item of prn::people:template/personPerson: Bob is an Item of prn::people:template/personEach PRN names the person Template of the people App.
Alice is now two Items. The user from chapter 2 makes calls and holds a Role. The person is what the people App knows about her. Nothing links the two, so run.ts keeps both Identifiers: people.alice is the user and persons.alice is the person.
2. Point a request at a person
Section titled “2. Point a request at a person”A Relation links one Item to another. In leave.ts, declare one from the leave request to the person, below the three Properties:
leaveRequest.addRelation('requester', 'many-to-one', person, { toKey: 'leave' });many-to-one says many requests point at one person. A request calls the Relation requester, and a person calls it leave.
Alice makes the request, so your handler loads the person as Alice. She needs a Grant to see it, and the people App grants its person to nobody. Add the Grant below the one on the leave request:
const colleagues = person.addRole('colleagues', async () => [employee.prn]); person.addGrant(colleagues, Object.values(person.properties));This is the Grant from chapter 2, on a Template your App imported. Every employee sees a person and its name.
A request now says who asked. Add requester to RequestInput:
readonly requester?: string;Then change request to set the Relation. The marked lines are new or changed:
const request = app.addMutation('request', async (input: RequestInput, current, ctx) => { const workspace = await ctx.getWorkspaceItem(); const item = await workspace.createChild(current.templates.leaveRequest, { properties: { days: input.days, reason: input.reason }, }); 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); } return item; }); request.input.addProperty('reason', 'string').mandatory(); request.input.addProperty('days', 'integer').mandatory(); request.input.addProperty('requester', 'id'); request.output.item(leaveRequest).mandatory();Your handler loads the person from the people App and points the new request at it. A request sent without a requester is saved as before, so the earlier calls in run.ts still work.
At the end of run.ts, above the last line, request two days of leave as Alice and send her person with it:
// Request two days of leave as Alice, for the person Alice.const conference = await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; const input = { days: 2, reason: 'Conference', requester: persons.alice }; return await leave.mutations.request.handler(input, leave, ctx);});console.log(`As Alice: "${conference.properties.reason}" is ${conference.state.value}`);Below that, follow the Relation from the request to the person:
// Follow the Relation from the request to the person.const requester = await as(people.alice, async (ctx) => { const item = await ctx.getItem(conference.id); const relation = item?.relations.requester; return relation?.type === 'one' ? await relation.get() : undefined;});console.log(`As Alice: "Conference" was requested by ${requester?.properties.name}`);Run it:
Person: Alice is an Item of prn::people:template/personPerson: Bob is an Item of prn::people:template/personAs Alice: "Conference" is pendingAs Alice: "Conference" was requested by Aliceget() returns the person the request points at. Alice reads the name of an Item that belongs to another App.
3. Count approvals for each person
Section titled “3. Count approvals for each person”A Metric counts Events, and a Dimension says who each count belongs to. In leave.ts, declare both below the remind Listener:
const approvals = app.addMetric('approvals'); approvals.addEvent(approvedEvent);
const byRequester = app.addMetricDimension('requester', [person]); approvals.addDimension(byRequester, 1, async (event, _dimension, ctx) => { const item = await ctx.getItem(event.itemId); const relation = item?.relations.requester; return relation?.type === 'one' ? await relation.get() : undefined; });Each approved Event adds 1 to approvals. For each Event, your handler loads the request, follows requester and returns the person, so the Metric keeps a count for each person. For a request with no requester it returns undefined, and the approval counts in the total only.
Run it. The output does not change, because nothing reads the Metric yet.
4. Read the Metric
Section titled “4. Read the Metric”A query does not count leave requests. It reads the counts that a projector builds from the saved Events, and your script has no projector. At the top of run.ts, import one below the harness import:
import { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';Register it below the line that creates the harness:
await harness.ticker.register(createSqliteProjector(runtime, { spec: leaveApp }));From now on, harness.tickAll() runs the projector with the rest of the queued work.
At the end of run.ts, above the last line, add a helper that reads the Metric, and call it:
// Read the approvals Metric: the total, and the count for Alice.const showApprovals = async () => { const report = await workspace.read(async (ctx) => { const metric = ctx.apps.leave.metrics.approvals; const byRequester = metric.dimensions.requester; const from = ctx.now.minus({ days: 7 }).toJSDate(); const to = ctx.now.toJSDate(); return await metric .query('count') .focalDimension(byRequester) .dimensions([byRequester]) .interval(from, to) .period('day') .execute(); }); const total = report.value ?? 0; const alice = report.entries.day.entries[persons.alice]?.value ?? 0; console.log(`Metric: ${total} approvals, ${alice} for Alice`);};await showApprovals();A query needs a focal Dimension, an interval and a period. Every query names a focal Dimension, and dimensions lists the Dimensions that break the result down. Here both are requester.
The interval is the last seven days on the script’s clock. The period is a label: with 'day', the count for each person sits under report.entries.day. report.value is the total, and null while nothing is counted. The entry under Alice’s Identifier holds her count.
Run it:
Person: Alice is an Item of prn::people:template/personPerson: Bob is an Item of prn::people:template/personAs Alice: "Conference" is pendingAs Alice: "Conference" was requested by AliceMetric: 2 approvals, 0 for AliceThe Metric holds two approvals already: “Summer holiday” from the Quickstart and “Long weekend” from chapter 2. The projector counted them in the harness.tickAll() calls earlier in the script. “Summer holiday” was canceled later and still counts, because a Metric counts Events, not the state of an Item. Neither request points at a person, so Alice has none.
5. Watch the count move
Section titled “5. Watch the count move”Approve Alice’s request as Bob, and read the Metric twice: before the queued work runs, and after. At the end of run.ts, above the last line:
// Approve the request as Bob. Show the Metric before and after the queued work runs.const counted = await as(people.bob, async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.approve.handler({ id: conference.id }, leave, ctx);});console.log(`As Bob: "${counted.properties.reason}" is ${counted.state.value}`);await showApprovals();await harness.tickAll();await showApprovals();Run it:
Person: Alice is an Item of prn::people:template/personPerson: Bob is an Item of prn::people:template/personAs Alice: "Conference" is pendingAs Alice: "Conference" was requested by AliceMetric: 2 approvals, 0 for AliceAs Bob: "Conference" is approvedMetric: 2 approvals, 0 for AliceListener: "Conference" is approvedMetric: 3 approvals, 1 for Aliceapprove returned with the request approved and the Event saved, and the Metric still read 2. The projector counted the Event when run.ts reached harness.tickAll(). The total is now 3, and 1 of them is Alice’s.
What you have now
Section titled “What you have now”- An imported App.
peopleholds thepersonItems. Your App reaches it throughaddDependencyinleave.tsand throughctx.apps.peoplewhen it runs. - A Relation across Apps. Each new request points at the person who asked for it, and employees see that person.
- A Metric with a Dimension.
approvalscounts everyapprovedEvent, in total and for each person. - A projector in your script.
harness.tickAll()runs it, so the count moves when the queued work runs.
The whole App
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
import { peopleApp } from './people';
interface RequestInput { readonly days: number; readonly reason: string; readonly requester?: string;}
interface IdInput { readonly id: string;}
interface RejectInput extends IdInput { readonly note?: string;}
export const leaveApp: AppSpec = (app) => { app.configure('leave');
const people = app.addDependency('people', peopleApp); const person = people.templates.person;
const employee = app.addRole('employee', { label: 'Employee' }); const manager = app.addRole('manager', { label: 'Manager' }); manager.extend(employee);
const leaveRequest = app.addTemplate('leaveRequest'); leaveRequest.addProperty('reason', 'string'); leaveRequest.addProperty('days', 'integer'); leaveRequest.addProperty('notice', 'string'); leaveRequest.addRelation('requester', 'many-to-one', person, { toKey: 'leave' });
const staff = leaveRequest.addRole('staff', async () => [employee.prn]); leaveRequest.addGrant(staff, Object.values(leaveRequest.properties));
const colleagues = person.addRole('colleagues', async () => [employee.prn]); person.addGrant(colleagues, Object.values(person.properties));
const pending = leaveRequest.addState('pending').setDefault(); const approved = leaveRequest.addState('approved'); pending.addTransition('approve', approved);
const rejected = leaveRequest.addState('rejected'); pending.addTransition('reject', rejected);
const canceled = leaveRequest.addState('canceled'); pending.addTransition('cancel', canceled); approved.addTransition('cancel', canceled);
const approvedEvent = leaveRequest.addEvent('approved'); approvedEvent.addListener('announce', async (_event, item) => { console.log(`Listener: "${item.properties.reason}" is approved`); });
const rejectedEvent = leaveRequest.addEvent('rejected'); rejectedEvent.input.addProperty('note', 'string'); rejectedEvent.addListener('notify', async (event, item) => { const note = event.payload.note; const notice = typeof note === 'string' ? `Rejected: ${note}` : 'Rejected'; await item.updateProperties({ notice }); });
const reminderDue = leaveRequest.addEvent('reminderDue'); reminderDue.addSchedule('weekdays', '0 9 * * 1-5').state(['pending']); reminderDue.addListener('remind', async (_event, item) => { await item.updateProperties({ notice: 'Waiting for a decision' }); });
const approvals = app.addMetric('approvals'); approvals.addEvent(approvedEvent);
const byRequester = app.addMetricDimension('requester', [person]); approvals.addDimension(byRequester, 1, async (event, _dimension, ctx) => { const item = await ctx.getItem(event.itemId); const relation = item?.relations.requester; return relation?.type === 'one' ? await relation.get() : undefined; });
const request = app.addMutation('request', async (input: RequestInput, current, ctx) => { const workspace = await ctx.getWorkspaceItem(); const item = await workspace.createChild(current.templates.leaveRequest, { properties: { days: input.days, reason: input.reason }, }); 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); } return item; }); request.input.addProperty('reason', 'string').mandatory(); request.input.addProperty('days', 'integer').mandatory(); request.input.addProperty('requester', 'id'); request.output.item(leaveRequest).mandatory();
const approve = app.addMutation('approve', async (input: IdInput, current) => { const item = await current.templates.leaveRequest.getItem(input.id); if (item === undefined || item.state?.value !== 'pending') { throw new Error('Leave request is not pending'); } const updated = await item.state.transitions.approve.execute({}); await updated.events.approved.publish({}); return updated; }); approve.input.addProperty('id', 'id').mandatory(); approve.output.item(leaveRequest).mandatory();
const reject = app.addMutation('reject', async (input: RejectInput, current) => { const item = await current.templates.leaveRequest.getItem(input.id); if (item === undefined || item.state?.value !== 'pending') { throw new Error('Leave request is not pending'); } const updated = await item.state.transitions.reject.execute({}); await updated.events.rejected.publish({ note: input.note }); return updated; }); reject.input.addProperty('id', 'id').mandatory(); reject.input.addProperty('note', 'string'); reject.output.item(leaveRequest).mandatory();
const cancel = app.addMutation('cancel', async (input: IdInput, current) => { const item = await current.templates.leaveRequest.getItem(input.id); if (item === undefined) throw new Error('Leave request not found'); const transition = item.state?.transitions.cancel; if (transition === undefined) { throw new Error(`A ${item.state?.value} leave request cannot be canceled`); } return await transition.execute({}); }); cancel.input.addProperty('id', 'id').mandatory(); cancel.output.item(leaveRequest).mandatory();
const list = app.addQuery('list', async (_input: unknown, current) => { const requests = current.templates.leaveRequest.selectItems(); const page = await requests.sort(['$createdAt asc']).execute(); return page.results; }); list.output.item(leaveRequest).array();
request.addGrant(employee); cancel.addGrant(employee); list.addGrant(employee); approve.addGrant(manager); reject.addGrant(manager);};The whole people App
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
export const peopleApp: AppSpec = (app) => { app.configure('people');
const person = app.addTemplate('person'); person.addProperty('name', 'string');};The whole run script
import type { SystemWriteRuntimeInstance, WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';import { createSqliteInstance } from '@pyn-backend/platform-reactor-sqlite';import { createSqlitePlatformService } from '@pyn-backend/platform-service-sqlite';import { createTestConfigurationService } from '@pyn-backend/service-configuration-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestDynamicConfigService } from '@pyn-backend/test-services-dynamic-config';import { createTestLoggerService } from '@pyn-backend/test-services-logger';
import { leaveApp } from './leave';
// A SQLite database, held in memory, with the Alpyne tables.const knex = await createSqliteKnexDatabase(':memory:');await knex.current.migrate.latest();
// The services a Runtime depends on.const system = createTestSystemService();const services = { configuration: createTestConfigurationService(), cron: createTestCronService({ system }), dynamicConfig: createTestDynamicConfigService(), knex, logger: createTestLoggerService(), system,};
// The SQLite Runtime with your App loaded, and a Workspace to hold its data.const platform = createSqlitePlatformService(services);const reactor = createSqliteInstance({ ...services, platform }, {});const runtime = { ...services, platform, reactor };const harness = await createHarnessInstance(runtime, leaveApp);await harness.ticker.register(createSqliteProjector(runtime, { spec: leaveApp }));const workspace = await harness.createWorkspace();console.log(`Leave App is running in Workspace ${workspace.workspaceId}`);
// Request five days of leave.const request = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; const input = { days: 5, reason: 'Summer holiday' }; return await leave.mutations.request.handler(input, leave, ctx);});console.log(`Requested: "${request.properties.reason}" is ${request.state.value}`);
// Approve the request.const approved = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.approve.handler({ id: request.id }, leave, ctx);});console.log(`Approved: "${approved.properties.reason}" is ${approved.state.value}`);
// Finish the work the App has queued, then close the database.await harness.tickAll();
// Request two days of leave and reject the request.const moving = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; const input = { days: 2, reason: 'Moving house' }; return await leave.mutations.request.handler(input, leave, ctx);});const rejected = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.reject.handler({ id: moving.id }, leave, ctx);});console.log(`Rejected: "${rejected.properties.reason}" is ${rejected.state.value}`);
// Cancel the approved request.const canceled = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.cancel.handler({ id: request.id }, leave, ctx);});console.log(`Canceled: "${canceled.properties.reason}" is ${canceled.state.value}`);
// List the requests with their states.const listRequests = async () => { const requests = await workspace.read(async (ctx) => { const leave = ctx.apps.leave; return await leave.queries.list.handler({}, leave, ctx); }); for (const item of requests) { console.log(`Listed: "${item.properties.reason}" is ${item.state.value}`); }};await listRequests();
// Try to cancel the rejected request.try { await workspace.write(async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.cancel.handler({ id: moving.id }, leave, ctx); });} catch (error) { console.log(`Refused: ${error instanceof Error ? error.message : String(error)}`);}await listRequests();
// Add two people. Alice is an employee and Bob is a manager.const people = await workspace.write(async (ctx) => { const root = await ctx.getWorkspaceItem(); const user = ctx.apps.identity.templates.user; const roles = ctx.apps.leave.roles; const templatePrn = 'prn::identity:template/user'; const alice = await user.createItem(root, { properties: { displayName: 'Alice' } }); const bob = await user.createItem(root, { properties: { displayName: 'Bob' } }); await roles.employee.assign({ id: alice.id, templatePrn }); await roles.manager.assign({ id: bob.id, templatePrn }); return { alice: alice.id, bob: bob.id };});for (const id of [people.alice, people.bob]) { const item = await workspace.read(async (ctx) => await ctx.getItem(id)); const person = item?.properties; console.log(`Joined: ${person?.displayName} holds ${person?.rolePrns.join(', ')}`);}
// Run a write as one person.const as = async <T>(id: string, fn: (ctx: WriteRuntimeInstance) => Promise<T>) => { const instance = await platform.createInstance({ identityId: crypto.randomUUID(), principalId: id, rolePrns: [], sessionId: crypto.randomUUID(), type: 'principal', workspaceId: workspace.workspaceId, }); return await instance.execute('readwrite', { payload: {}, traceId: 'tutorial' }, fn);};
// Request three days of leave as Alice.const weekend = await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; const input = { days: 3, reason: 'Long weekend' }; return await leave.mutations.request.handler(input, leave, ctx);});console.log(`As Alice: "${weekend.properties.reason}" is ${weekend.state.value}`);
// Try to approve the request as Alice.try { await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.approve.handler({ id: weekend.id }, leave, ctx); });} catch (error) { const reason = error instanceof Error ? error.message : String(error); console.log(`As Alice: Refused. ${reason}`);}
// Approve the request as Bob, then finish the work the App has queued.const decided = await as(people.bob, async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.approve.handler({ id: weekend.id }, leave, ctx);});console.log(`As Bob: "${decided.properties.reason}" is ${decided.state.value}`);await harness.tickAll();
// Request one day of leave as Alice, then reject it as Bob with a note.const dentist = await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; const input = { days: 1, reason: 'Dentist' }; return await leave.mutations.request.handler(input, leave, ctx);});const refused = await as(people.bob, async (ctx) => { const leave = ctx.apps.leave; const input = { id: dentist.id, note: 'Team offsite' }; return await leave.mutations.reject.handler(input, leave, ctx);});console.log(`As Bob: "${refused.properties.reason}" is ${refused.state.value}`);
// Read the Events saved for the request.const history = await workspace.write(async (ctx: SystemWriteRuntimeInstance) => { const page = await ctx.selectEvents().itemId(dentist.id).execute(); return page.results;});for (const event of history) { console.log(`Event: ${event.eventPrn} ${JSON.stringify(event.payload)}`);}
// Print the notice Alice sees on a request.const showNotice = async (id: string) => { const item = await as(people.alice, async (ctx) => await ctx.getItem(id)); const notice = item?.properties.notice; const text = notice === undefined ? 'no notice' : `the notice "${notice}"`; console.log(`As Alice: "${item?.properties.reason}" has ${text}`);};
// Show the notice before and after the queued work runs.await showNotice(dentist.id);await harness.tickAll();await showNotice(dentist.id);
// Request two days of leave as Alice. Nobody decides.const wedding = await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; const input = { days: 2, reason: 'Wedding' }; return await leave.mutations.request.handler(input, leave, ctx);});console.log(`As Alice: "${wedding.properties.reason}" is ${wedding.state.value}`);
// Run the queued work. The clock has not moved.await harness.tickAll();console.log(`Clock: ${system.current.toUTCString()}`);await showNotice(wedding.id);
// Move the clock forward one day, then run the queued work.await harness.tickAll({ days: 1 });console.log(`Clock: ${system.current.toUTCString()}`);await showNotice(wedding.id);await showNotice(dentist.id);
// Add Alice and Bob to the people App.const persons = await workspace.write(async (ctx) => { const root = await ctx.getWorkspaceItem(); const person = ctx.apps.people.templates.person; const alice = await person.createItem(root, { properties: { name: 'Alice' } }); const bob = await person.createItem(root, { properties: { name: 'Bob' } }); return { alice: alice.id, bob: bob.id };});for (const id of [persons.alice, persons.bob]) { const item = await workspace.read(async (ctx) => await ctx.getItem(id)); console.log(`Person: ${item?.properties.name} is an Item of ${item?.templatePrn}`);}
// Request two days of leave as Alice, for the person Alice.const conference = await as(people.alice, async (ctx) => { const leave = ctx.apps.leave; const input = { days: 2, reason: 'Conference', requester: persons.alice }; return await leave.mutations.request.handler(input, leave, ctx);});console.log(`As Alice: "${conference.properties.reason}" is ${conference.state.value}`);
// Follow the Relation from the request to the person.const requester = await as(people.alice, async (ctx) => { const item = await ctx.getItem(conference.id); const relation = item?.relations.requester; return relation?.type === 'one' ? await relation.get() : undefined;});console.log(`As Alice: "Conference" was requested by ${requester?.properties.name}`);
// Read the approvals Metric: the total, and the count for Alice.const showApprovals = async () => { const report = await workspace.read(async (ctx) => { const metric = ctx.apps.leave.metrics.approvals; const byRequester = metric.dimensions.requester; const from = ctx.now.minus({ days: 7 }).toJSDate(); const to = ctx.now.toJSDate(); return await metric .query('count') .focalDimension(byRequester) .dimensions([byRequester]) .interval(from, to) .period('day') .execute(); }); const total = report.value ?? 0; const alice = report.entries.day.entries[persons.alice]?.value ?? 0; console.log(`Metric: ${total} approvals, ${alice} for Alice`);};await showApprovals();
// Approve the request as Bob. Show the Metric before and after the queued work runs.const counted = await as(people.bob, async (ctx) => { const leave = ctx.apps.leave; return await leave.mutations.approve.handler({ id: conference.id }, leave, ctx);});console.log(`As Bob: "${counted.properties.reason}" is ${counted.state.value}`);await showApprovals();await harness.tickAll();await showApprovals();
await knex.destroy();The whole tutorial
Section titled “The whole tutorial”This is the last chapter. You started with the Quickstart’s leave request, which was pending or approved. Now it is a small App:
- A lifecycle. Four states, and a refusal for a move you did not declare. Chapter 1.
- Access rules. Two Roles, a Grant on every operation, and calls made as Alice and as Bob. Chapter 2.
- Work after a decision. Events with payloads, Listeners, and a schedule on a clock you move. Chapter 3.
- Composition and measurement. An imported App, a Relation to its people, and a Metric. This chapter.
All of it is two Apps and one script: leave.ts, people.ts and run.ts.
Next steps
Section titled “Next steps”Each guide takes one part of the App further.

