Example

This example models an example fulfilment process once a customer has purchased an item from an online store.

// fulfiment-workflow-state.ts
import { WorkflowState } from '@node-ts/bus-core'

export class FulfilmentWorkflowState extends WorkflowState {
  static NAME = 'FulfilmentWorkflowState'
  $name = FulfilmentWorkflowState.NAME

  itemId: string
  customerId: string
  status: 'email-receipt' | 'shipping-item' | 'complete'
}
import { BusInstance } from '@node-ts/bus-core'

export class FulfilmentWorkflow extends Workflow<FulfilmentWorkflowState> {

  constructor (bus: BusInstance) {}
  
  configureWorkflow (
    mapper: WorkflowMapper<FulfilmentWorkflowState, FulfilmentWorkflow>
  ): void {
    mapper
      .withState(FulfilmentWorkflowState)
      .startedBy(ItemPurchased, 'shipItem')
      .when(ItemShipped, 'emailReceipt')
      .when(ReceiptEmailed, 'complete')
  }
  
  async shipItem ({ itemId, customerId }: ItemPurchased) {
    await this.bus.send(new ShipItem(itemId, customerId))
    return { itemId, customerId, status: 'shipping-item' }
  }
  
  async emailReceipt (_: ItemShipped, { itemId, customerId }: FulfilmentWorkflowState) {
    await this.bus.send(new EmailReceipt(itemId, customerId))
    return { status: 'emailing-receipt' }
  }
  
  async complete () {
    return this.completeWorkflow({ status: 'complete' })
  }
}

Last updated