Raw
1 import { CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Workflows`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn about workflows and how to define and execute them.
10
11 ## What is a Workflow?
12
13 In digital commerce you typically have many systems involved in your operations. For example, you may have an ERP system that holds product master data and accounting reports, a CMS system for content, a CRM system for managing customer campaigns, a payment service to process credit cards, and so on. Sometimes you may even have custom built applications that need to participate in the commerce stack. One of the biggest challenges when operating a stack like this is ensuring consistency in the data spread across systems.
14
15 Medusa has a built-in durable execution engine to help complete tasks that span multiple systems. You orchestrate your operations across systems in Medusa instead of having to manage it yourself. Other commerce platforms don't have this capability, which makes them a bottleneck to building customizations and iterating quickly.
16
17 A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow similar to how you create a JavaScript function.
18
19 However, unlike regular functions, workflows:
20
21 - Create an internal representation of your steps, allowing you to track them and their progress.
22 - Support defining roll-back logic for each step, so that you can handle errors gracefully and your data remain consistent across systems.
23 - Perform long actions asynchronously, giving you control over when a step starts and finishes.
24
25 You implement all custom flows within workflows, then execute them from [API routes](../api-routes/page.mdx), [subscribers](../../fundamentals/events-and-subscribers/page.mdx), and [scheduled jobs](../../fundamentals/scheduled-jobs/page.mdx).
26
27 ---
28
29 ## How to Create and Execute a Workflow?
30
31 ### 1. Create the Steps
32
33 A workflow is made of a series of steps. A step is created using `createStep` from the Workflows SDK.
34
35 Create the file `src/workflows/hello-world.ts` with the following content:
36
37 ![Example of workflow file in the application's directory structure](https://res.cloudinary.com/dza7lstvk/image/upload/v1732866980/Medusa%20Book/workflow-dir-overview_xklukj.jpg)
38
39 export const step1Highlights = [
40 ["4", `"step-1"`, "The step's unique name."],
41 ["6", "`Hello from step one!`", "The step's returned data."]
42 ]
43
44 ```ts title="src/workflows/hello-world.ts" highlights={step1Highlights}
45 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
46
47 const step1 = createStep(
48 "step-1",
49 async () => {
50 return new StepResponse(`Hello from step one!`)
51 }
52 )
53 ```
54
55 The `createStep` function accepts the step's unique name as a first parameter, and the step's function as a second parameter.
56
57 Steps must return an instance of `StepResponse`, whose parameter is the data to return to the workflow executing the step.
58
59 Steps can accept input parameters. For example, add the following to `src/workflows/hello-world.ts`:
60
61 export const step2Highlights = [
62 ["7", "name", "Receive step input as a parameter."]
63 ]
64
65 ```ts title="src/workflows/hello-world.ts" highlights={step2Highlights}
66 type WorkflowInput = {
67 name: string
68 }
69
70 const step2 = createStep(
71 "step-2",
72 async ({ name }: WorkflowInput) => {
73 return new StepResponse(`Hello ${name} from step two!`)
74 }
75 )
76 ```
77
78 This adds another step whose function accepts as a parameter an object with a `name` property.
79
80 ### 2. Create a Workflow
81
82 Next, add the following to the same file to create the workflow using the `createWorkflow` function:
83
84 export const workflowHighlights = [
85 ["10", `"hello-world"`, "The workflow's unique name."],
86 ["11", "input", "The workflow's input is passed as a parameter."],
87 ["16", "WorkflowResponse", "The workflow returns an instance of WorkflowResponse."]
88 ]
89
90 ```ts title="src/workflows/hello-world.ts" highlights={workflowHighlights}
91 import {
92 // other imports...
93 createWorkflow,
94 WorkflowResponse,
95 } from "@medusajs/framework/workflows-sdk"
96
97 // ...
98
99 const myWorkflow = createWorkflow(
100 "hello-world",
101 function (input: WorkflowInput) {
102 const str1 = step1()
103 // to pass input
104 const str2 = step2(input)
105
106 return new WorkflowResponse({
107 message: str2,
108 })
109 }
110 )
111
112 export default myWorkflow
113 ```
114
115 The `createWorkflow` function accepts the workflow's unique name as a first parameter, and the workflow's function as a second parameter. The workflow can accept input which is passed as a parameter to the function.
116
117 The workflow must return an instance of `WorkflowResponse`, whose parameter is returned to workflow executors.
118
119 ### 3. Execute the Workflow
120
121 You can execute a workflow from different customizations:
122
123 - Execute in an API route to expose the workflow's functionalities to clients.
124 - Execute in a subscriber to use the workflow's functionalities when a commerce operation is performed.
125 - Execute in a scheduled job to run the workflow's functionalities automatically at a specified repeated interval.
126
127 To execute the workflow, invoke it passing the [Medusa container](../medusa-container/page.mdx) as a parameter. Then, use its `run` method:
128
129 <CodeTabs group="resource-types">
130 <CodeTab label="API Route" value="api-route">
131
132 ```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"], ["13"], ["14"], ["15"], ["16"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
133 import type {
134 MedusaRequest,
135 MedusaResponse,
136 } from "@medusajs/framework/http"
137 import myWorkflow from "../../workflows/hello-world"
138
139 export async function GET(
140 req: MedusaRequest,
141 res: MedusaResponse
142 ) {
143 const { result } = await myWorkflow(req.scope)
144 .run({
145 input: {
146 name: "John",
147 },
148 })
149
150 res.send(result)
151 }
152 ```
153
154 </CodeTab>
155 <CodeTab label="Subscriber" value="subscriber">
156
157 ```ts title="src/subscribers/order-placed.ts" highlights={[["11"], ["12"], ["13"], ["14"], ["15"], ["16"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
158 import {
159 type SubscriberConfig,
160 type SubscriberArgs,
161 } from "@medusajs/framework"
162 import myWorkflow from "../workflows/hello-world"
163
164 export default async function handleOrderPlaced({
165 event: { data },
166 container,
167 }: SubscriberArgs<{ id: string }>) {
168 const { result } = await myWorkflow(container)
169 .run({
170 input: {
171 name: "John",
172 },
173 })
174
175 console.log(result)
176 }
177
178 export const config: SubscriberConfig = {
179 event: "order.placed",
180 }
181 ```
182
183 </CodeTab>
184 <CodeTab label="Scheduled Job" value="scheduled-job">
185
186 ```ts title="src/jobs/message-daily.ts" highlights={[["7"], ["8"], ["9"], ["10"], ["11"], ["12"]]}
187 import { MedusaContainer } from "@medusajs/framework/types"
188 import myWorkflow from "../workflows/hello-world"
189
190 export default async function myCustomJob(
191 container: MedusaContainer
192 ) {
193 const { result } = await myWorkflow(container)
194 .run({
195 input: {
196 name: "John",
197 },
198 })
199
200 console.log(result.message)
201 }
202
203 export const config = {
204 name: "run-once-a-day",
205 schedule: `0 0 * * *`,
206 };
207 ```
208
209 </CodeTab>
210 </CodeTabs>
211
212 ### 4. Test Workflow
213
214 To test out your workflow, start your Medusa application:
215
216 ```bash npm2yarn
217 npm run dev
218 ```
219
220 Then, if you added the API route above, send a `GET` request to `/workflow`:
221
222 ```bash
223 curl http://localhost:9000/workflow
224 ```
225
226 You’ll receive the following response:
227
228 ```json title="Example Response"
229 {
230 "message": "Hello John from step two!"
231 }
232 ```
233
234 ---
235
236 ## Access Medusa Container in Workflow Steps
237
238 A step receives an object as a second parameter with configurations and context-related properties. One of these properties is the `container` property, which is the [Medusa container](../medusa-container/page.mdx) to allow you to resolve Framework and commerce tools in your application.
239
240 For example, consider you want to implement a workflow that returns the total products in your application. Create the file `src/workflows/product-count.ts` with the following content:
241
242 export const highlights = [
243 ["11", "container", "Receive the Medusa container as a parameter"],
244 ["12", "resolve", "Resolve the Product Module's main service."],
245 [
246 "13",
247 `Modules.PRODUCT`,
248 "The resource registration name.",
249 ],
250 ]
251
252 ```ts title="src/workflows/product-count.ts" highlights={highlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
253 import {
254 createStep,
255 StepResponse,
256 createWorkflow,
257 WorkflowResponse,
258 } from "@medusajs/framework/workflows-sdk"
259 import { Modules } from "@medusajs/framework/utils"
260
261 const getProductCountStep = createStep(
262 "get-product-count",
263 async (_, { container }) => {
264 const productModuleService = container.resolve(
265 Modules.PRODUCT
266 )
267
268 const [, count] = await productModuleService.listAndCountProducts()
269
270 return new StepResponse(count)
271 }
272 )
273
274 const productCountWorkflow = createWorkflow(
275 "product-count",
276 function () {
277 const count = getProductCountStep()
278
279 return new WorkflowResponse({
280 count,
281 })
282 }
283 )
284
285 export default productCountWorkflow
286 ```
287
288 In `getProductCountStep`, you use the `container` to resolve the Product Module's main service. Then, you use its `listAndCountProducts` method to retrieve the total count of products and return it in the step's response. You then execute this step in the `productCountWorkflow`.
289
290 You can now execute this workflow in a custom API route, scheduled job, or subscriber to get the total count of products.
291
292 <Note title="Tip">
293
294 Find a full list of the registered resources in the Medusa container and their registration key in [this reference](!resources!/medusa-container-resources). You can use these resources in your custom workflows.
295
296 </Note>