Skip to content

Relate items

Declare a Relation when two Items have their own lifecycles and one refers to the other. Use this guide instead of the hierarchy when the link is not parent-child, or when an Item links to many others.

  • The Templates on both ends, declared as in Define data.
  • A Union, declared with app.addUnion(key, [templates]), when one end accepts several Templates.
  1. Declare the Relation. On the from-side Template, call addRelation(key, cardinality, to, { toKey }). The cardinality is 'one-to-one', 'one-to-many', 'many-to-one' or 'many-to-many', read from the from-side to the to-side. to is a Template or a Union. key names the Relation on from-side Items and toKey names it on to-side Items. toKey defaults to key; set it whenever the two directions read differently, as with manager and reports.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  2. Narrow the side you hold. item.relations.<key> is a one-side instance when the other end holds at most one Item and a many-side instance otherwise; its type is 'one' or 'many'. Check type before calling side-specific methods. For employee.relations.manager the type is 'one'; for manager.relations.reports it is 'many'.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  3. Set a one-side target with set(target). It replaces any existing target and resolves true only when no target was set before. setIfNotExists(target, condition) leaves an existing target in place and resolves false, so a Mutation that runs twice does not reassign the desk. The optional { existingMaxAge } condition, in milliseconds, treats an older target as replaceable. clear() removes the target.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  4. Add many-side targets with add(target) or add([targets]). Adding a target that is already present resolves false and changes nothing. addIfNotExists(target, condition) makes that idempotency explicit and accepts the same age condition. remove(target) drops one target and clear() drops them all. Every target must belong to the Relation’s to-side Template or Union; the Runtime rejects any other Item.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  5. Navigate a one side with get(). It resolves the target as a RelatedItem or undefined. A RelatedItem is the target Item plus a relation block with createdAt, fromId, toId and relationPrn. Read underlyingItem when you pass the target on, for example as a parent to createChild or into another set.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  6. Navigate a many side with select(). It returns a selector over the targets, so limit, cursor, paginate, sort and archived apply. Await execute() for the results, or first() for one target. Each result is a RelatedItem carrying its own relation metadata.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };
  7. Target a Union to accept several Templates. employee.relations.assets accepts a desk or a laptop because asset is a Union of both. Look the target up through current.unions.asset.getItem(id), and navigate back from either member Template through the Relation’s toKey.

    examples/relationships/staffing.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    import type { ReadAppInstance } from '@alpynehq/alpyne-types/runtime';
    interface AssignDeskInput {
    readonly deskId: string;
    readonly employeeId: string;
    }
    interface SetManagerInput {
    readonly employeeId: string;
    readonly managerId: string;
    }
    interface JoinProjectInput {
    readonly employeeId: string;
    readonly projectId: string;
    }
    interface IssueAssetInput {
    readonly assetId: string;
    readonly employeeId: string;
    }
    interface EmployeeInput {
    readonly employeeId: string;
    }
    interface AssetInput {
    readonly assetId: string;
    }
    export const staffApp: AppSpec = (app) => {
    app.configure('staffing');
    const employee = app.addTemplate('employee');
    employee.addProperty('name', 'string');
    const desk = app.addTemplate('desk');
    desk.addProperty('label', 'string');
    const laptop = app.addTemplate('laptop');
    laptop.addProperty('serial', 'string');
    const project = app.addTemplate('project');
    project.addProperty('name', 'string');
    const asset = app.addUnion('asset', [desk, laptop]);
    employee.addRelation('desk', 'one-to-one', desk, { toKey: 'occupant' });
    employee.addRelation('manager', 'many-to-one', employee, { toKey: 'reports' });
    project.addRelation('members', 'many-to-many', employee, { toKey: 'projects' });
    employee.addRelation('assets', 'one-to-many', asset, { toKey: 'holder' });
    const assignDesk = app.addMutation('assignDesk', async (input: AssignDeskInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const target = await current.templates.desk.getItem(input.deskId);
    if (occupant === undefined || target === undefined) throw new Error('Employee or desk not found');
    const relation = occupant.relations.desk;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    return await relation.setIfNotExists(target);
    });
    assignDesk.input.addProperty('employeeId', 'id').mandatory();
    assignDesk.input.addProperty('deskId', 'id').mandatory();
    assignDesk.output.value('boolean').mandatory();
    const setManager = app.addMutation('setManager', async (input: SetManagerInput, current) => {
    const report = await current.templates.employee.getItem(input.employeeId);
    const manager = await current.templates.employee.getItem(input.managerId);
    if (report === undefined || manager === undefined) throw new Error('Employee not found');
    const relation = report.relations.manager;
    if (relation.type !== 'one') throw new Error('Expected a one-side Relation');
    await relation.set(manager);
    });
    setManager.input.addProperty('employeeId', 'id').mandatory();
    setManager.input.addProperty('managerId', 'id').mandatory();
    setManager.output.void();
    const joinProject = app.addMutation('joinProject', async (input: JoinProjectInput, current) => {
    const team = await current.templates.project.getItem(input.projectId);
    const member = await current.templates.employee.getItem(input.employeeId);
    if (team === undefined || member === undefined) throw new Error('Project or employee not found');
    const relation = team.relations.members;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.addIfNotExists(member);
    });
    joinProject.input.addProperty('projectId', 'id').mandatory();
    joinProject.input.addProperty('employeeId', 'id').mandatory();
    joinProject.output.value('boolean').mandatory();
    const issueAsset = app.addMutation('issueAsset', async (input: IssueAssetInput, current) => {
    const holder = await current.templates.employee.getItem(input.employeeId);
    const issued = await current.unions.asset.getItem(input.assetId);
    if (holder === undefined || issued === undefined) throw new Error('Employee or asset not found');
    const relation = holder.relations.assets;
    if (relation.type !== 'many') throw new Error('Expected a many-side Relation');
    return await relation.add(issued);
    });
    issueAsset.input.addProperty('employeeId', 'id').mandatory();
    issueAsset.input.addProperty('assetId', 'id').mandatory();
    issueAsset.output.value('boolean').mandatory();
    const deskOf = app.addQuery('deskOf', async (input: EmployeeInput, current) => {
    const occupant = await current.templates.employee.getItem(input.employeeId);
    const relation = occupant?.relations.desk;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    deskOf.input.addProperty('employeeId', 'id').mandatory();
    deskOf.output.item(desk);
    const reports = app.addQuery('reports', async (input: EmployeeInput, current: ReadAppInstance) => {
    const manager = await current.templates.employee.getItem(input.employeeId);
    const relation = manager?.relations.reports;
    if (relation === undefined || relation.type !== 'many') return [];
    const selected = await relation.select().execute();
    return selected.results.map((related) => related.underlyingItem);
    });
    reports.input.addProperty('employeeId', 'id').mandatory();
    reports.output.item(employee).array();
    const holderOf = app.addQuery('holderOf', async (input: AssetInput, current) => {
    const issued = await current.unions.asset.getItem(input.assetId);
    const relation = issued?.relations.holder;
    if (relation === undefined || relation.type !== 'one') return undefined;
    return (await relation.get())?.underlyingItem;
    });
    holderOf.input.addProperty('assetId', 'id').mandatory();
    holderOf.output.item(employee);
    };

The test below assigns a desk twice, sets a manager, joins a project twice, issues two kinds of asset, and reads every Relation back from both sides.

examples/relationships/staffing.test.ts
import type { ReadItem } from '@alpynehq/alpyne-types/runtime';
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 { staffApp } from './staffing';
describe('relate items', () => {
it('sets, adds and navigates Relations of every cardinality', 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 }, staffApp);
const workspace = await harness.createWorkspace();
// The harness runs every execution as system.
const ids = await workspace.write(async (ctx) => {
const { desk, employee, laptop, project } = ctx.apps.staffing.templates;
const root = await ctx.getWorkspaceItem();
const manager = await root.createChild(employee, { properties: { name: 'Grace' } });
const report = await root.createChild(employee, { properties: { name: 'Linus' } });
const corner = await root.createChild(desk, { properties: { label: 'Corner' } });
const window = await root.createChild(desk, { properties: { label: 'Window' } });
const machine = await root.createChild(laptop, { properties: { serial: 'X1' } });
const launch = await root.createChild(project, { properties: { name: 'Launch' } });
return { corner: corner.id, launch: launch.id, machine: machine.id, manager: manager.id, report: report.id, window: window.id };
});
await workspace.write(async (ctx) => {
const current = ctx.apps.staffing;
const { assignDesk, issueAsset, joinProject, setManager } = current.mutations;
expect(await assignDesk.handler({ deskId: ids.corner, employeeId: ids.report }, current, ctx)).toBe(true);
expect(await assignDesk.handler({ deskId: ids.window, employeeId: ids.report }, current, ctx)).toBe(false);
await setManager.handler({ employeeId: ids.report, managerId: ids.manager }, current, ctx);
expect(await joinProject.handler({ employeeId: ids.report, projectId: ids.launch }, current, ctx)).toBe(true);
expect(await joinProject.handler({ employeeId: ids.report, projectId: ids.launch }, current, ctx)).toBe(false);
expect(await issueAsset.handler({ assetId: ids.corner, employeeId: ids.report }, current, ctx)).toBe(true);
expect(await issueAsset.handler({ assetId: ids.machine, employeeId: ids.report }, current, ctx)).toBe(true);
});
await workspace.read(async (ctx) => {
const current = ctx.apps.staffing;
const { deskOf, holderOf, reports } = current.queries;
expect((await deskOf.handler({ employeeId: ids.report }, current, ctx))?.properties.label).toBe('Corner');
expect((await reports.handler({ employeeId: ids.manager }, current, ctx)).map((item: ReadItem) => item.id)).toStrictEqual([ids.report]);
expect((await holderOf.handler({ assetId: ids.machine }, current, ctx))?.id).toBe(ids.report);
const report = await current.templates.employee.getItem(ids.report);
const assets = report?.relations.assets;
if (assets === undefined || assets.type !== 'many') throw new Error('Expected a many-side Relation');
const issued = await assets.select().execute();
expect(issued.results.map((related) => related.templatePrn).sort()).toStrictEqual([
'prn::staffing:template/desk',
'prn::staffing:template/laptop',
]);
expect(issued.results[0]?.relation.fromId).toBe(ids.report);
});
expect.assertions(11);
});
});

From the repository root, run:

Terminal window
pnpm run cli test alpynehq/alpyne/website/examples/relationships/

You should see:

Test Files 1 passed (1)
Tests 1 passed (1)

The second assignDesk and joinProject calls resolve false because the link already exists. reports lists the employee from the manager’s side, holderOf navigates from a Union member back to the employee, and the selected assets carry relation.fromId.

  • addRelation(...).evented() declares an Event on the from-side Template that the Runtime publishes with action, otherId and relationPrn whenever the Relation is set, added, removed or cleared.
  • relation.isType(item) reports whether an Item belongs to the other end of the Relation, for narrowing before set or add.