---
url: https://node-ts.github.io/bus/api/bus-core/functions/defineWorkflow.md
---
[API reference](../../index.md) / [@node-ts/bus-core](../index.md) / defineWorkflow

# Function: defineWorkflow()

```ts
function defineWorkflow<TWorkflowState>(workflowStateType): FunctionWorkflow<TWorkflowState>;
```

Defined in: [packages/bus-core/src/workflow/define-workflow.ts:288](https://github.com/node-ts/bus/blob/2e6cf65c27833b707ae31ee623cfb6343770f434/packages/bus-core/src/workflow/define-workflow.ts#L288)

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`](../classes/WorkflowState.md) |

## Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `workflowStateType` | [`WorkflowStateConstructor`](../type-aliases/WorkflowStateConstructor.md)<`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`](../interfaces/FunctionWorkflow.md)<`TWorkflowState`>

A workflow with no handlers. Add them with `startedBy` and `when`.

## Example

```ts
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)
```
