Skip to content

Split a product into Apps

An App that has grown splits into smaller ones. Give each thing that other Apps will want an App of its own, and keep every App short enough to read in one sitting. The people who use the product get the answers they got before.

This page splits one App in two, and shows where each declaration went and why.

Room bookings that refuse a clash is one App, bookings, of about 120 lines. It holds rooms and bookings together: two Templates, a Relation between them, one Role, three operations, and an App Hook that gives every Workspace two rooms.

Rooms are the part another App would want, so they get an App of their own. This is the whole of it:

rooms.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
export const roomsApp: AppSpec = (app) => {
app.configure('rooms');
const manager = app.addRole('manager', { label: 'Room manager' });
const room = app.addTemplate('room');
room.addProperty('name', 'string');
const managers = room.addRole('managers', async () => [manager.prn]);
room.addGrant(managers, Object.values(room.properties));
app.onCreate(async (prev, current, ctx) => {
await prev();
const workspace = await ctx.getWorkspaceItem();
for (const name of ['Maple', 'Oak']) {
const key = name.toLowerCase();
await workspace.createChild(current.templates.room, { key, properties: { name } });
}
});
};

rooms.ts never names a booking. It holds the room Template and the hook, as the one App had them. It adds one Role, manager, with a Grant that shows a room to the people who hold it. With that Role the App also works where no App imports it: a manager finds the two rooms.

bookings imports the rooms App and keeps the rest. These are its declarations:

bookings.ts
app.configure('bookings');
const staff = app.addRole('staff', { label: 'Staff' });
const room = app.addDependency('rooms', roomsApp).templates.room;
const booking = app.addTemplate('booking');
booking.addProperty('bookedBy', 'id');
booking.addProperty('start', 'datetime');
booking.addProperty('end', 'datetime');
booking.addRelation('room', 'many-to-one', room, { toKey: 'bookings' });
const everyStaff = async () => [staff.prn];
const roomStaff = room.addRole('staff', everyStaff);
room.addGrant(roomStaff, Object.values(room.properties));
const bookingStaff = booking.addRole('staff', everyStaff);
booking.addGrant(bookingStaff, Object.values(booking.properties));
const booked = booking.addState('booked').setDefault();
const canceled = booking.addState('canceled');
booked.addTransition('cancel', canceled);

The helpers and the three operations follow. They are the lines of the example, but for the lines that find a room in book and in free.

The whole of bookings.ts
bookings.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
import type { ReadItem, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
import { roomsApp } from './rooms';
interface SlotInput {
readonly from: number;
readonly to: number;
}
interface BookInput extends SlotInput {
readonly room: string;
}
interface IdInput {
readonly id: string;
}
export const bookingsApp: AppSpec = (app) => {
app.configure('bookings');
const staff = app.addRole('staff', { label: 'Staff' });
const room = app.addDependency('rooms', roomsApp).templates.room;
const booking = app.addTemplate('booking');
booking.addProperty('bookedBy', 'id');
booking.addProperty('start', 'datetime');
booking.addProperty('end', 'datetime');
booking.addRelation('room', 'many-to-one', room, { toKey: 'bookings' });
const everyStaff = async () => [staff.prn];
const roomStaff = room.addRole('staff', everyStaff);
room.addGrant(roomStaff, Object.values(room.properties));
const bookingStaff = booking.addRole('staff', everyStaff);
booking.addGrant(bookingStaff, Object.values(booking.properties));
const booked = booking.addState('booked').setDefault();
const canceled = booking.addState('canceled');
booked.addTransition('cancel', canceled);
// The start and the end of a slot, as times on the day of the call.
const timesOf = (ctx: ReadRuntimeInstance, slot: SlotInput) => {
if (slot.to <= slot.from) throw new Error('A slot ends after it starts');
const day = ctx.now.startOf('day');
const start = day.plus({ hours: slot.from });
return { end: day.plus({ hours: slot.to }), start };
};
// The times, as text, of the first booking of a room that is still booked and overlaps a slot.
const findClash = async (ctx: ReadRuntimeInstance, target: ReadItem, slot: SlotInput) => {
const { end, start } = timesOf(ctx, slot);
const bookings = target.relations.bookings;
if (bookings.type !== 'many') return undefined;
const stillBooked = bookings.select().state(['booked']);
for await (const other of stillBooked.iterator()) {
const { end: until, start: since } = other.propertyValues;
if (since?.type !== 'datetime' || until?.type !== 'datetime') continue;
if (since.value < end && start < until.value) {
return `${since.value.toFormat('HH:mm')} to ${until.value.toFormat('HH:mm')}`;
}
}
return undefined;
};
const book = app.addMutation('book', async (input: BookInput, current, ctx) => {
const template = ctx.apps.rooms.templates.room;
const target = await template.selectItems().key(input.room).first();
if (target === undefined) throw new Error('Room not found');
const clash = await findClash(ctx, target, input);
const name = target.properties.name;
if (clash !== undefined) throw new Error(`${name} is booked from ${clash}`);
const workspace = await ctx.getWorkspaceItem();
const item = await workspace.createChild(current.templates.booking, {
properties: { bookedBy: ctx.principalId, ...timesOf(ctx, input) },
});
const relation = item.relations.room;
if (relation.type === 'one') await relation.set(target);
return item;
});
book.input.addProperty('room', 'string').mandatory();
book.input.addProperty('from', 'number').mandatory();
book.input.addProperty('to', 'number').mandatory();
book.output.item(booking).mandatory();
const cancel = app.addMutation('cancel', async (input: IdInput, current, ctx) => {
const item = await current.templates.booking.getItem(input.id);
if (item === undefined) throw new Error('Booking not found');
if (item.properties.bookedBy !== ctx.principalId) {
throw new Error('Only the person who booked can cancel');
}
const transition = item.state?.transitions.cancel;
if (transition === undefined) throw new Error('The booking is already canceled');
return await transition.execute({});
});
cancel.input.addProperty('id', 'id').mandatory();
cancel.output.item(booking).mandatory();
const free = app.addQuery('free', async (input: SlotInput, _current, ctx) => {
const template = ctx.apps.rooms.templates.room;
const page = await template.selectItems().sort(['$createdAt asc']).execute();
const rooms: ReadItem[] = page.results;
const clashes = await Promise.all(rooms.map((item) => findClash(ctx, item, input)));
return rooms.filter((_item, index) => clashes[index] === undefined);
});
free.input.addProperty('from', 'number').mandatory();
free.input.addProperty('to', 'number').mandatory();
free.output.item(room).array();
book.addGrant(staff);
cancel.addGrant(staff);
free.addGrant(staff);
};

Each row is one kind of declaration, and the App that holds it now.

What Which App Why
The room Template rooms Nothing in a room names a booking, so the Template stands without one
The hook that saves Maple and Oak rooms It creates rooms. It runs where rooms is the root App, and where another App imports it
A Role and a Grant for the people who manage rooms rooms New. They show a room to the App’s own people
The staff Role bookings Every operation it opens is an operation of bookings
The Template Role and the Grant that show a room to staff bookings, on the Template it imports Staff are people of bookings. rooms.ts does not name them
The booking Template, its states and its transition bookings They did not change
The Relation between a booking and its room bookings The App that needs the Relation declares it, and each side reads it under its own key
book, cancel and free bookings Each applies a rule about bookings. free answers with rooms, by the rule book uses
The lines of a handler that find a room bookings, through ctx.apps.rooms current is the App of the handler, which no longer holds the Template
bookings.ts
const room = app.addDependency('rooms', roomsApp).templates.room;
const booking = app.addTemplate('booking');
booking.addProperty('bookedBy', 'id');
booking.addProperty('start', 'datetime');
booking.addProperty('end', 'datetime');
booking.addRelation('room', 'many-to-one', room, { toKey: 'bookings' });

addDependency adds the rooms App to the application, and templates.room on what it returns is that App’s Template. addRelation takes it as it took the App’s own Template before.

The Relation is a declaration of bookings: its PRN is prn::bookings:template/booking/relation/room. A booking reads it as room. A room, an Item of the rooms App, reads the other side as bookings, and findClash walks a room’s bookings that way, as it did.

bookings.ts
const everyStaff = async () => [staff.prn];
const roomStaff = room.addRole('staff', everyStaff);
room.addGrant(roomStaff, Object.values(room.properties));

These lines did not change. room is now the imported Template, so bookings.ts adds a Template Role and a Grant to a Template of the rooms App. Staff find a room through them, and a manager finds it through the Grant in rooms.ts. A manager finds no booking, and a person who holds neither Role finds no room.

A handler finds a room through the imported App

Section titled “A handler finds a room through the imported App”
bookings.ts
const template = ctx.apps.rooms.templates.room;
const target = await template.selectItems().key(input.room).first();
if (target === undefined) throw new Error('Room not found');

In the one App, book read current.templates.room. current is the App of the handler, bookings, and it no longer holds that Template. A handler reaches every App of the application in ctx.apps, under the name the App gave configure. free changed the same way.

The script of the example runs the two Apps as it stands: run.ts is the same file, byte for byte. It imports ./bookings, and that App brings the rooms App with it. It prints what the one App prints:

Bookings App is running in Workspace 7c5a4e9b-b240-54cf-b7f8-382a9e65507f
Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is booked
Clock: Wed, 01 Jan 2020 09:00:00 GMT
As Bob: Refused. Maple is booked from 10:00 to 11:00
As Bob: Oak, Wed, 01 Jan 2020 10:30 to 11:30, is booked
As Bob: free from 10:00 to 11:00: no room
As Bob: free from 11:30 to 12:30: Maple, Oak
As Bob: Refused. Only the person who booked can cancel
As Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is canceled
As Bob: free from 10:00 to 11:00: Maple
As Bob: Maple, Wed, 01 Jan 2020 10:30 to 11:30, is booked

The people and their Roles are the same. staff is still a Role of bookings, and the script assigns it where it did:

run.ts
const people = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const user = ctx.apps.identity.templates.user;
const roles = ctx.apps.bookings.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.staff.assign({ id: alice.id, templatePrn });
await roles.staff.assign({ id: bob.id, templatePrn });
return { alice: alice.id, bob: bob.id };
});

Every operation is still an operation of bookings, so every call goes where it went. Staff get the same answers, call for call. The Runtime refuses each operation to a person with no Role, with the same message.

Two things changed, and the script touches neither:

  • A room is an Item of prn::rooms:template/room. It was an Item of prn::bookings:template/room.
  • A caller that reads the Template itself finds it in ctx.apps.rooms. ctx.apps.bookings no longer holds it.

The first matters for a Workspace that already holds rooms. The rooms it saved stay under the old PRN, and the two Apps do not find them: free lists no room, and book answers Room not found. Change a live App shows what a Template under a new name does to saved Items. Move a Template before a Workspace holds its Items.

  • Split out what a second App will want to import. rooms.ts names nothing of bookings, so another App imports it as it stands. Two Apps that import one App share it: what one saves there, the other reads.
  • Keep an operation with the Template whose rule it enforces. free returns rooms, but its rule is about bookings that overlap. It stays beside book, and both ask findClash.
  • Declare from the App that needs it. The Relation to a room, and the Role and Grant that show a room to staff, are lines of bookings.ts. rooms.ts did not change to take them.
  • A Listener belongs to the App that reacts. In Employee onboarding checklists, the people App publishes joined. The onboarding App declares the Listener that makes the checklist.