Define data
Declare a Template for each kind of Item your App persists, then create Items below the Workspace Item or another parent. Use this guide when a new kind of data enters your App.
Before you start
Section titled “Before you start”- A configured App, as built in Your first application.
zodimported in the App module when a Property holds structured JSON.
-
Declare the Template. On the App, call
addTemplate(key)once per kind of Item. The key names the Template in every PRN beneath it, for exampleprn::directory:template/team. A key starts with a lowercase letter, continues with letters and digits, and runs to 64 characters;rootis reserved.examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);}; -
Add primitive and temporal Properties. On the Template, call
addProperty(key, type, options). Primitive types are'string','integer','number','boolean'and'id'. Temporal types are'date','time','datetime','instant'and'duration'. Adatetimeorinstantvalue is a LuxonDateTime, soctx.nowwrites straight into one. The options carry alabelfor generated assets and aformatsuch as'email'for a string. Chain.index()on a Property that selectors filter or sort by. The Property keysidandstateare reserved.examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);}; -
Add select and JSON Properties. A
'single-select'or'multi-select'Property returns a builder withaddOption(key, { color, icon, label }). A stored value that names no option reads asnullfor a single select and as an empty array for a multi select. Pass a Zod object type such asz.object({ ... })instead of a type name to declare a JSON Property parsed by it.examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);}; -
Add Workspace-level Properties. Call
app.getWorkspaceTemplate().addProperty(key, type)for a value that belongs to the Workspace as a whole, such as a time zone. Read and write it through the Workspace Item fromctx.getWorkspaceItem().examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);}; -
Create Items in a Mutation. In a write execution,
parent.createChild(template, { key, properties, state })places the new Item belowparent, andcurrent.templates.employee.createItem(parent, options)does the same from the Template side. Top-level Items hang offctx.getWorkspaceItem(). A key is unique among one parent’s children: creating another child with the same key moves that key to the new child.examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);}; -
Address Items by key path.
ctx.getItemByKeyPath('platform', 'ada')walks from the Workspace Item one key per level and returnsundefinedwhen any level is missing.ctx.getItem(id)andcurrent.templates.employee.getItem(id)address an Item by Identifier;parent.getChildByKey(key)descends one level.examples/define-data/directory.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { z } from 'zod';interface CreateTeamInput {readonly key: string;readonly name: string;}interface HireInput {readonly email: string;readonly key: string;readonly level: string;readonly name: string;readonly teamKey: string;}interface FindInput {readonly employeeKey: string;readonly teamKey: string;}export const directoryApp: AppSpec = (app) => {app.configure('directory');const team = app.addTemplate('team');team.addProperty('name', 'string').index();team.addProperty('headcount', 'integer');team.addProperty('founded', 'date');team.addProperty('remote', 'boolean');const employee = app.addTemplate('employee');employee.addProperty('name', 'string', { label: 'Full name' });employee.addProperty('email', 'string', { format: 'email' }).index();employee.addProperty('startedAt', 'datetime');const level = employee.addProperty('level', 'single-select');level.addOption('junior', { label: 'Junior' });level.addOption('senior', { label: 'Senior' });level.addOption('lead', { label: 'Lead' });const skills = employee.addProperty('skills', 'multi-select');skills.addOption('typescript', {});skills.addOption('postgresql', {});employee.addProperty('address', z.object({ city: z.string(), country: z.string() }));app.getWorkspaceTemplate().addProperty('timezone', 'string');const createTeam = app.addMutation('createTeam', async (input: CreateTeamInput, current, ctx) => {const workspace = await ctx.getWorkspaceItem();return await workspace.createChild(current.templates.team, {key: input.key,properties: { headcount: 0, name: input.name, remote: false },});});createTeam.input.addProperty('key', 'string').mandatory();createTeam.input.addProperty('name', 'string').mandatory();createTeam.output.item(team);const hire = app.addMutation('hire', async (input: HireInput, current, ctx) => {const parent = await ctx.getItemByKeyPath(input.teamKey);if (parent === undefined) throw new Error(`Team ${input.teamKey} not found`);return await current.templates.employee.createItem(parent, {key: input.key,properties: { email: input.email, level: input.level, name: input.name, startedAt: ctx.now },});});hire.input.addProperty('teamKey', 'string').mandatory();hire.input.addProperty('key', 'string').mandatory();hire.input.addProperty('name', 'string').mandatory();hire.input.addProperty('email', 'string').mandatory();hire.input.addProperty('level', 'string').mandatory();hire.output.item(employee);const find = app.addQuery('find', async (input: FindInput, _current, ctx) => {return await ctx.getItemByKeyPath(input.teamKey, input.employeeKey);});find.input.addProperty('teamKey', 'string').mandatory();find.input.addProperty('employeeKey', 'string').mandatory();find.output.item(employee);};
Verify
Section titled “Verify”The test below creates a keyed team, hires a keyed employee below it, and reads both back by key path and Identifier through the App’s Query.
import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createTestPlatformService } from '@pyn-backend/platform-service-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { describe, expect, it } from 'vitest';
import { directoryApp } from './directory';
describe('define data', () => { it('creates keyed Items in the hierarchy and reads them back by key path', async () => { const system = createTestSystemService(); const logger = createTestLoggerService(); const cron = createTestCronService({ system }); const platform = createTestPlatformService({ cron, logger, system }); const harness = await createHarnessInstance({ cron, logger, platform, system }, directoryApp); const workspace = await harness.createWorkspace();
// The harness runs every execution as system. const ids = await workspace.write(async (ctx) => { const current = ctx.apps.directory; const team = await current.mutations.createTeam.handler({ key: 'platform', name: 'Platform' }, current, ctx); const hired = await current.mutations.hire.handler( { email: 'ada@example.com', key: 'ada', level: 'lead', name: 'Ada Lovelace', teamKey: 'platform' }, current, ctx, ); await hired.updateProperties({ address: { city: 'London', country: 'GB' }, skills: ['typescript'] }); const root = await ctx.getWorkspaceItem(); await root.updateProperties({ timezone: 'Europe/London' }); return { employee: hired.id, team: team.id }; });
await workspace.read(async (ctx) => { const current = ctx.apps.directory; const found = await current.queries.find.handler({ employeeKey: 'ada', teamKey: 'platform' }, current, ctx); const team = await ctx.getItem(ids.team); const root = await ctx.getWorkspaceItem();
expect(found?.id).toBe(ids.employee); expect(found?.key).toBe('ada'); expect(found?.parentId).toBe(ids.team); expect(found?.templatePrn).toBe('prn::directory:template/employee'); expect(found?.properties.level).toBe('lead'); expect(found?.properties.skills).toStrictEqual(['typescript']); expect(found?.properties.address).toStrictEqual({ city: 'London', country: 'GB' }); expect(found?.propertyValues.startedAt.type).toBe('datetime'); expect(team?.properties.headcount).toBe(0); expect(root?.properties.timezone).toBe('Europe/London'); }); expect.assertions(10); });});From the repository root, run:
pnpm run cli test alpynehq/alpyne/website/examples/define-data/You should see:
Test Files 1 passed (1) Tests 1 passed (1)The assertions confirm that the child’s parentId is the team and its templatePrn is prn::directory:template/employee. Each Property reads back with its declared type: the select as an option key, the JSON as the parsed object and the datetime as a tagged value in propertyValues.
Options
Section titled “Options”parent.upsertChildByKey(template, { key, properties })creates the child when the key is free and writes the supplied Properties to the existing child otherwise.upsertChildrenByKeydoes the same for a map of keys.template.setExtensible()lets each parent Item declare additional Properties for its children throughitem.extensions(template).property.unique()declares a Property whose value is unique for the Template within a Workspace.setDescription(text)on a Template or Property andsetLabel(text)on a Property feed the generated reference and application assets.
Related
Section titled “Related”- Data model for how Templates, Items, Properties and the hierarchy fit together.
- Relate items to link Items across Templates instead of nesting them.
- Handle incomplete data to read values that are absent, mismatched or filtered.
- Data and identity for the rules every Runtime follows when storing Items.
TemplateBuilderandBaseWriteItemfor every declaration and creation method.

