API reference / @node-ts/bus-core / defineWorkflow
Function: defineWorkflow()
function defineWorkflow<TWorkflowState>(workflowStateType): FunctionWorkflow<TWorkflowState>;Defined in: packages/bus-core/src/workflow/define-workflow.ts:288
Declares a workflow with plain functions, as an alternative to a class that extends Workflow. Its handlers get the message, the workflow state and a WorkflowContext to send, publish, read the message attributes and end the workflow, so they need no container and can be unit tested by calling them directly.
Register it with Bus.configure().withWorkflow(workflow). It's handled, persisted and retried the same way as a class workflow. The workflow state class is in the message types that bus generate-message-types generates, so its Dates, Maps, Sets and classes are restored.
Type Parameters
| Type Parameter |
|---|
TWorkflowState extends WorkflowState |
Parameters
| Parameter | Type | Description |
|---|---|---|
workflowStateType | WorkflowStateConstructor<TWorkflowState> | The class of the workflow's state. It extends WorkflowState, has a unique $name and is constructed with no arguments. Its $name is the name of the workflow. |
Returns
FunctionWorkflow<TWorkflowState>
A workflow with no handlers. Add them with startedBy and when.
Example
export const orderWorkflow = defineWorkflow(OrderState)
.startedBy(OrderPlaced, async (message, _state, ctx) => {
await ctx.send(new ChargeCard(message.orderId))
return { orderId: message.orderId }
})
.when(CardCharged, { lookup: m => m.orderId, mapsTo: 'orderId' }, (_message, _state, ctx) =>
ctx.complete({ charged: true })
)
Bus.configure().withWorkflow(orderWorkflow)