|
1
|
# Custom Workflows |
|
2
|
|
|
3
|
A workflow is a series of queries and actions that complete a task. |
|
4
|
|
|
5
|
The workflow is created in a TypeScript or JavaScript file under the `src/workflows` directory. |
|
6
|
|
|
7
|
For example: |
|
8
|
|
|
9
|
```ts |
|
10
|
import { |
|
11
|
createStep, |
|
12
|
createWorkflow, |
|
13
|
WorkflowResponse, |
|
14
|
StepResponse, |
|
15
|
} from "@medusajs/framework/workflows-sdk" |
|
16
|
|
|
17
|
const step1 = createStep("step-1", async () => { |
|
18
|
return new StepResponse(`Hello from step one!`) |
|
19
|
}) |
|
20
|
|
|
21
|
type WorkflowInput = { |
|
22
|
name: string |
|
23
|
} |
|
24
|
|
|
25
|
const step2 = createStep( |
|
26
|
"step-2", |
|
27
|
async ({ name }: WorkflowInput) => { |
|
28
|
return new StepResponse(`Hello ${name} from step two!`) |
|
29
|
} |
|
30
|
) |
|
31
|
|
|
32
|
type WorkflowOutput = { |
|
33
|
message1: string |
|
34
|
message2: string |
|
35
|
} |
|
36
|
|
|
37
|
const helloWorldWorkflow = createWorkflow( |
|
38
|
"hello-world", |
|
39
|
(input: WorkflowInput) => { |
|
40
|
const greeting1 = step1() |
|
41
|
const greeting2 = step2(input) |
|
42
|
|
|
43
|
return new WorkflowResponse({ |
|
44
|
message1: greeting1, |
|
45
|
message2: greeting2 |
|
46
|
}) |
|
47
|
} |
|
48
|
) |
|
49
|
|
|
50
|
export default helloWorldWorkflow |
|
51
|
``` |
|
52
|
|
|
53
|
## Execute Workflow |
|
54
|
|
|
55
|
You can execute the workflow from other resources, such as API routes, scheduled jobs, or subscribers. |
|
56
|
|
|
57
|
For example, to execute the workflow in an API route: |
|
58
|
|
|
59
|
```ts |
|
60
|
import type { |
|
61
|
MedusaRequest, |
|
62
|
MedusaResponse, |
|
63
|
} from "@medusajs/framework" |
|
64
|
import myWorkflow from "../../../workflows/hello-world" |
|
65
|
|
|
66
|
export async function GET( |
|
67
|
req: MedusaRequest, |
|
68
|
res: MedusaResponse |
|
69
|
) { |
|
70
|
const { result } = await myWorkflow(req.scope) |
|
71
|
.run({ |
|
72
|
input: { |
|
73
|
name: req.query.name as string, |
|
74
|
}, |
|
75
|
}) |
|
76
|
|
|
77
|
res.send(result) |
|
78
|
} |
|
79
|
``` |