Documentation

5.7.12. Execute Another Workflow

In this chapter, you'll learn how to execute a workflow in another.

Execute in a Workflow#

To execute a workflow in another, use the runAsStep method that every workflow has.

For example:

Code
6} from "@medusajs/core-flows"7
8const workflow = createWorkflow(9  "hello-world",10  async (input) => {11    const products = createProductsWorkflow.runAsStep({12      input: {13        products: [14          // ...15        ],16      },17    })18
19    // ...20  }21)

Instead of invoking the workflow, passing it the container, you use its runAsStep method and pass it an object as a parameter.

The object has an input property to pass input to the workflow.


Preparing Input Data#

If you need to perform some data manipulation to prepare the other workflow's input data, use the transform utility function imported from @medusajs/workflows-sdk.

NoteLearn about the transform utility in this chapter .

For example:

Code
11}12
13const workflow = createWorkflow(14  "hello-product",15  async (input: WorkflowInput) => {16    const createProductsData = transform({17      input,18    }, (data) => [19      {20        title: `Hello ${data.input.title}`,21      },22    ])23
24    const products = createProductsWorkflow.runAsStep({25      input: {26        products: createProductsData,27      },28    })29
30    // ...31  }32)

In this example, you use the transform function to prepend Hello to the title of the product. Then, you pass the result as an input to the createProductsWorkflow.


Run Workflow Conditionally#

To run a workflow in another based on a condition, use the when-then utility functions imported from @medusajs/workflows-sdk.

NoteLearn about the when-then utility in this chapter .

For example:

Code
15}16
17const workflow = createWorkflow(18  "hello-product",19  async (input: WorkflowInput) => {20    const product = when(input, ({ should_create }) => should_create)21      .then(() => {22        return createProductsWorkflow.runAsStep({23          input: {24            products: [input.product],25          },26        })27      })28  }29)

In this example, you use the when utility to run the createProductsWorkflow only if should_create (passed in the input) is enabled.

Was this chapter helpful?
Edit this page