5.8.2. Conditions in Workflows with When-Then

In this chapter, you'll learn how to execute an action based on a condition in a workflow using the when-then utility.

Why If-Conditions Aren't Allowed in Workflows?#

Medusa creates an internal representation of the workflow definition you pass to createWorkflow to track and store its steps.

At that point, variables in the workflow don't have any values. They only do when you execute the workflow.

So, you can't use an if-condition that checks a variable's value, as the condition will be evaluated when Medusa creates the internal representation of the workflow, rather than during execution.

Instead, use the when-then utility.


What is the When-Then Utility?#

The when-then utility functions execute an action if a condition is satisfied.

The when function accepts as a parameter a function that returns a boolean value, and the then function is chained to when. then accepts as a parameter a function that's executed if when's parameter function returns a true value.

For example:

Code
1import { 2  createWorkflow,3  WorkflowResponse,4  when,5} from "@medusajs/framework/workflows-sdk"6// step imports...7
8const workflow = createWorkflow(9  "workflow", 10  function (input: {11    is_active: boolean12  }) {13
14    const result = when(15      input, 16      (input) => {17        return input.is_active18      }19    ).then(() => {20      const stepResult = isActiveStep()21      return stepResult22    })23
24    // executed without condition25    const anotherStepResult = anotherStep(result)26
27    return new WorkflowResponse(28      anotherStepResult29    )30  }31)

In this code snippet, you execute the isActiveStep only if the input.is_active's value is true.

When Parameters#

when utility is a function imported from @medusajs/framework/workflows-sdk. It accepts the following parameters:

  1. The first parameter is either an object or the workflow's input. This data is passed as a parameter to the function in when's second parameter.
  2. The second parameter is a function that returns a boolean indicating whether to execute the action in then.

Then Parameters#

To specify the action to perform if the condition is satisfied, chain a then function to when and pass it a callback function.

The callback function is only executed if when's second parameter function returns a true value.

Was this chapter helpful?
Edit this page