Skip to content

createProcessManager

Process managers are created via eventStore.createProcessManager(name). They coordinate workflows across multiple aggregate roots by listening for events and issuing commands in response.

const pm = eventStore.createProcessManager('cascade-delete')

Streams that handlers dispatch commands on are settled automatically when the handler completes — calling settled() inside a process manager throws. The optional second parameter declares defaults for those auto-settles, most notably a concurrency retry for unattended writes:

const pm = eventStore.createProcessManager('cascade-delete', {
settled: { maxRetries: 3 },
})

See Retrying on concurrency conflicts for the retry semantics and the purity requirement it places on the dispatched commands.

Defines optional internal state. The state is persisted alongside checkpoints and restored on catch-up.

pm.withState({ pendingDeletions: [] })

Registers event handlers named on{EventName}. If state was defined, accepts a callback receiving the state.

// Without state
pm.withEventHandlers({
async onOrganizationDeleted({ streamId }) {
const users = await db.select().from(usersTable)
.where(eq(usersTable.orgId, streamId))
for (const user of users) {
userRoot.loadStream(user.id).delete()
}
},
})
// With state
pm.withEventHandlers((state) => ({
async onUserCreated({ payload }) {
state.userCount++
},
}))

Each handler receives (event, { refreshing }) where refreshing is true during a refresh operation.

Registers handlers that run after all on{EventName} handlers have completed. Uses the after{EventName} naming convention.

pm.withAfterEffects({
async afterOrderCompleted({ payload }) {
await sendConfirmationEmail(payload.email)
},
})

Disables the default exclusive per-stream locking.

Available only when .withState() has been called:

MethodReturn TypeDescription
.state()Promise<State>Returns current state after all pending events have been processed.
.refreshState()Promise<void>Full state refresh — replays all events from scratch.

Returns a promise that resolves when the process manager has finished its initial catch-up.

import { isInsideProcessManager, getProcessManagerInfo } from '@requence/event-sourcing'
FunctionReturn TypeDescription
isInsideProcessManager()booleantrue if called within a process manager event handler.
getProcessManagerInfo(){ name, event } | undefinedReturns the process manager name and triggering event.