5.8.1. Variable Manipulation in Workflows with transform

In this chapter, you'll learn how to manipulate variables in a workflow using the transform utility.

Why Variable Manipulation isn'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 only pass variables as parameters to steps. But, in a workflow, you can't change a variable's value or, if the variable is an array, loop over its items.

Instead, use the transform utility.


What is the transform Utility?#

The transform utility function creates a new variable as the result of manipulating other variables.

For example, consider you have two strings as the output of two steps:

Code
1const str1 = step1()2const str2 = step2()

To concatenate the strings, you create a new variable str3 using the transform function:

Code
1import { 2  createWorkflow,3  WorkflowResponse,4  transform,5} from "@medusajs/framework/workflows-sdk"6// step imports...7
8const myWorkflow = createWorkflow(9  "hello-world", 10  function (input) {11    const str1 = step1(input)12    const str2 = step2(input)13
14    const str3 = transform(15      { str1, str2 },16      (data) => `${data.str1}${data.str2}`17    )18
19    return new WorkflowResponse(str3)20  }21)

The transform utility function is imported from @medusajs/framework/workflows-sdk. It accepts two parameters:

  1. The first parameter is an object of variables to manipulate. The object is passed as a parameter to transform's second parameter function.
  2. The second parameter is the function performing the variable manipulation.

The value returned by the second parameter function is returned by transform. So, the str3 variable holds the concatenated string.

You can use the returned value in the rest of the workflow, either to pass it as an input to other steps or to return it in the workflow's response.


Example: Looping Over Array#

Use transform to loop over arrays to create another variable from the array's items.

For example:

Code
6// step imports...7
8type WorkflowInput = {9  items: {10    id: string11    name: string12  }[]13}14
15const myWorkflow = createWorkflow(16  "hello-world", 17  function ({ items }: WorkflowInput) {18    const ids = transform(19      { items },20      (data) => data.items.map((item) => item.id)21    )22    23    doSomethingStep(ids)24
25    // ...26  }27)

This workflow receives an items array in its input.

You use the transform utility to create an ids variable, which is an array of strings holding the id of each item in the items array.

You then pass the ids variable as a parameter to the doSomethingStep.

Was this chapter helpful?
Edit this page