Tutorial: the lifecycle
The Quickstart left you with a leave request that is pending or approved. A real one is also rejected, or canceled when plans change. In this chapter you give the request that lifecycle, one move at a time, and then try a move you did not declare.
What you build
Section titled “What you build”stateDiagram-v2 direction LR [*] --> pending pending --> approved: approve approved --> canceled: cancel pending --> canceled: cancel pending --> rejected: reject
Four states and four transitions. The Quickstart declared pending, approved and approve. You add the rest.
Before you start
Section titled “Before you start”You need leave.ts and run.ts from the Quickstart, with all five steps done. You 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 approved1. Reject a request
Section titled “1. Reject a request”A manager says no. In leave.ts, declare a rejected state and a reject transition that leads to it, below the approve transition:
const rejected = leaveRequest.addState('rejected'); pending.addTransition('reject', rejected);Three Mutations take a request’s Identifier from here on. Rename ApproveInput to IdInput, in the interface and in approve. Then add reject at the end of the App, above the closing };:
const reject = app.addMutation('reject', 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'); } return await item.state.transitions.reject.execute({}); }); reject.input.addProperty('id', 'id').mandatory(); reject.output.item(leaveRequest).mandatory();reject works like approve, without the Event. It checks that the request is pending, runs the transition and returns the request in its new state.
In run.ts, add two calls between await harness.tickAll(); and await knex.destroy();. The first requests two days of leave. The second rejects that request.
// 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}`);Run it. You should see one new line:
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 rejected2. Cancel a request
Section titled “2. Cancel a request”Plans change. A request is canceled while it is pending, or after it is approved. In leave.ts, declare a canceled state and a cancel transition from each of those two states, below reject:
const canceled = leaveRequest.addState('canceled'); pending.addTransition('cancel', canceled); approved.addTransition('cancel', canceled);Both transitions have the key cancel. A transition belongs to the state it leaves, so each state has its own cancel.
Add the Mutation below reject:
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();cancel does not check for one state. It asks the request for its cancel transition. A request has only the transitions declared on its current state, so transition is undefined when the request is rejected or already canceled.
At the end of run.ts, above the last line, cancel the request you approved:
// 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}`);Run it. The approved request is now canceled:
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 canceled3. List the requests
Section titled “3. List the requests”So far you see a request only when a Mutation returns it. In leave.ts, add a Query below cancel. It returns up to 100 leave requests, oldest first.
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();A Query reads and never writes. output.item(leaveRequest).array() declares what it returns: an array of leave requests.
At the end of run.ts, above the last line, call the Query and print each request. A Query only reads, so call it in workspace.read.
// 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();Run it. Each request shows the state its last move left it in:
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 rejected4. Try a move you did not declare
Section titled “4. Try a move you did not declare”No transition leaves rejected. At the end of run.ts, above the last line, try to cancel the rejected request anyway:
// 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();Run it. The App refuses, and the list is the same as before:
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 rejectedYou declared no cancel transition on rejected, so the rejected request has none. cancel throws, and the request stays rejected. approve and reject throw too when a request is not pending.
What you have now
Section titled “What you have now”- A full lifecycle. A leave request is
pending,approved,rejectedorcanceled, and moves only along the four transitions you declared. - A Mutation for every move.
requestcreates a leave request.approve,rejectandcancelmove it. - A Query.
listshows where each request stands.
The whole App
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface RequestInput { readonly days: number; readonly reason: string;}
interface IdInput { readonly id: string;}
export const leaveApp: AppSpec = (app) => { app.configure('leave');
const leaveRequest = app.addTemplate('leaveRequest'); leaveRequest.addProperty('reason', 'string'); leaveRequest.addProperty('days', 'integer');
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 request = app.addMutation('request', async (input: RequestInput, current, ctx) => { const workspace = await ctx.getWorkspaceItem(); return await workspace.createChild(current.templates.leaveRequest, { properties: { days: input.days, reason: input.reason }, }); }); request.input.addProperty('reason', 'string').mandatory(); request.input.addProperty('days', 'integer').mandatory(); 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: 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'); } return await item.state.transitions.reject.execute({}); }); reject.input.addProperty('id', 'id').mandatory(); 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();};The whole run script
import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';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);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();
await knex.destroy();Next steps
Section titled “Next steps”Your script runs every call as the system, and the system passes every Grant check. The next chapter of the tutorial covers who can do what, with Roles and Grants.

