Skip to content

Do something after a write commits

Publish an Event in the Mutation that makes the write, and add a Listener to the Event. The Mutation returns with the write and the Event saved. The Runtime runs the Listener after that, when the queued work runs.

In the leave App, a manager rejects a request with a note. reject executes the transition, then publishes rejected with the note as its payload:

leave.ts
const reject = app.addMutation('reject', async (input: RejectInput, current) => {
const item = await current.templates.leaveRequest.getItem(input.id);
if (item === undefined || item.state?.value !== 'pending') {
throw new Error('Leave request is not pending');
}
const updated = await item.state.transitions.reject.execute({});
await updated.events.rejected.publish({ note: input.note });
return updated;
});

The notify Listener gets the Event and the request it was published for. It saves a notice on the request:

leave.ts
const rejectedEvent = leaveRequest.addEvent('rejected');
rejectedEvent.input.addProperty('note', 'string');
rejectedEvent.addListener('notify', async (event, item) => {
const note = event.payload.note;
const notice = typeof note === 'string' ? `Rejected: ${note}` : 'Rejected';
await item.updateProperties({ notice });
});

Bob rejects “Dentist”. The script prints the saved Event, then the notice Alice sees, before and after it runs the queued work with harness.tickAll():

As Bob: "Dentist" is rejected
Event: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}
As Alice: "Dentist" has no notice
As Alice: "Dentist" has the notice "Rejected: Team offsite"

Look at the last two lines. The request has no notice when reject returns, and has one once the queued work has run.

The Listener has not run when the Mutation returns. A read made straight after the call finds the write, and not what the Listener does.

The whole App, built step by step: Tutorial: what happens next.