1 import { CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Emit Workflow and Service Events`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn about event types and how to emit an event in a service or workflow.
10
11 ## Event Types
12
13 In your customization, you can emit an event, then listen to it in a subscriber and perform an asynchronus action, such as send a notification or data to a third-party system.
14
15 There are two types of events in Medusa:
16
17 1. Workflow event: an event that's emitted in a workflow after a commerce feature is performed. For example, Medusa emits the `order.placed` event after a cart is completed.
18 2. Service event: an event that's emitted to track, trace, or debug processes under the hood. For example, you can emit an event with an audit trail.
19
20 ### Which Event Type to Use?
21
22 **Workflow events** are the most common event type in development, as most custom features and customizations are built around workflows.
23
24 Some examples of workflow events:
25
26 1. When a user creates a blog post and you're emitting an event to send a newsletter email.
27 2. When you finish syncing products to a third-party system and you want to notify the admin user of new products added.
28 3. When a customer purchases a digital product and you want to generate and send it to them.
29
30 You should only go for a **service event** if you're emitting an event for processes under the hood that don't directly affect front-facing features.
31
32 Some examples of service events:
33
34 1. When you're tracing data manipulation and changes, and you want to track every time some custom data is changed.
35 2. When you're syncing data with a search engine.
36
37 ---
38
39 ## Emit Event in a Workflow
40
41 To emit a workflow event, use the `emitEventStep` helper step provided in the `@medusajs/medusa/core-flows` package. It allows you to emit an event from within a workflow, and it only emits the event after the workflow has finished successfully.
42
43 For example:
44
45 export const highlights = [
46 ["13", "emitEventStep", "Emit an event."],
47 ["14", `eventName`, "The name of the event to emit."],
48 ["15", "data", "The data payload to pass with the event."]
49 ]
50
51 ```ts highlights={highlights}
52 import {
53 createWorkflow,
54 } from "@medusajs/framework/workflows-sdk"
55 import {
56 emitEventStep,
57 } from "@medusajs/medusa/core-flows"
58
59 const helloWorldWorkflow = createWorkflow(
60 "hello-world",
61 () => {
62 // ...
63
64 emitEventStep({
65 eventName: "custom.created",
66 data: {
67 id: "123",
68 // other data payload
69 },
70 })
71 }
72 )
73 ```
74
75 The `emitEventStep` accepts an object having the following properties:
76
77 - `eventName`: The event's name.
78 - `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
79
80 In this example, you emit the event `custom.created` and pass in the data payload an ID property.
81
82 ### Test it Out
83
84 If you execute the workflow, the event is emitted and you can see it in your application's logs.
85
86 Any subscribers listening to the event are executed.
87
88 ### Emit Event Multiple Times
89
90 You can also emit the event multiple times with `emitEventStep` by passing an array of objects to the `data` property. The event is emitted once per each object in the array.
91
92 For example:
93
94 ```ts highlights={highlights}
95 import {
96 createWorkflow,
97 } from "@medusajs/framework/workflows-sdk"
98 import {
99 emitEventStep,
100 } from "@medusajs/medusa/core-flows"
101
102 const helloWorldWorkflow = createWorkflow(
103 "hello-world",
104 () => {
105 // ...
106
107 emitEventStep({
108 eventName: "custom.created",
109 data: [
110 { id: "123" },
111 { id: "456" },
112 { id: "789" },
113 ],
114 })
115 }
116 )
117 ```
118
119 The event `custom.created` will be emitted three times, once per each object in the array passed to the `data` property. The subscriber listening to the event will be executed three times, each time receiving one of the objects in the array as the event's payload.
120
121 ### Emit Event with Custom Priority
122
123 <Note>
124
125 Event priority is available since [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0).
126
127 </Note>
128
129 You can specify a priority level when emitting events to control when the event is processed relative to other events in the queue. This is useful to ensure that critical business events are handled promptly, while less important events can be deferred.
130
131 To emit an event with custom priority, pass the `priority` property in the `options` parameter:
132
133 export const priorityHighlights = [
134 ["14", "priority", "Set the event priority to critical."]
135 ]
136
137 ```ts highlights={priorityHighlights}
138 import {
139 createWorkflow,
140 } from "@medusajs/framework/workflows-sdk"
141 import { emitEventStep } from "@medusajs/medusa/core-flows"
142 import { EventPriority } from "@medusajs/framework/utils"
143
144 const criticalWorkflow = createWorkflow(
145 "critical-operation",
146 () => {
147 emitEventStep({
148 eventName: "payment.processed",
149 data: { id: "123" },
150 options: {
151 priority: EventPriority.CRITICAL,
152 },
153 })
154 }
155 )
156 ```
157
158 In the above example, the `payment.processed` event is emitted with the `CRITICAL` priority level, ensuring it is processed before other lower-priority events.
159
160 Learn more in the [Event Processing Priority guide](../event-priority/page.mdx).
161
162 ---
163
164 ## Emit Event in a Service
165
166 To emit a service event:
167
168 1. Resolve `event_bus` from the module's container in your service's constructor:
169
170 <Note>
171
172 The Event Module's service (`event_bus`) is available in every module's container by default. You don't need to add it to `dependencies` in `medusa-config.ts`.
173
174 </Note>
175
176 <CodeTabs group="service_type">
177 <CodeTab label="Extending Service Factory" value="service_factory">
178
179 ```ts title="src/modules/blog/service.ts" highlights={["9"]}
180 import { IEventBusService } from "@medusajs/framework/types"
181 import { MedusaService } from "@medusajs/framework/utils"
182
183 class BlogModuleService extends MedusaService({
184 Post,
185 }){
186 protected eventBusService_: AbstractEventBusModuleService
187
188 constructor({ event_bus }) {
189 super(...arguments)
190 this.eventBusService_ = event_bus
191 }
192 }
193 ```
194
195 </CodeTab>
196 <CodeTab label="Without Service Factory" value="no_service_factory">
197
198 ```ts title="src/modules/blog/service.ts" highlights={["6"]}
199 import { IEventBusService } from "@medusajs/framework/types"
200
201 class BlogModuleService {
202 protected eventBusService_: AbstractEventBusModuleService
203
204 constructor({ event_bus }) {
205 this.eventBusService_ = event_bus
206 }
207 }
208 ```
209
210 </CodeTab>
211 </CodeTabs>
212
213 2. Use the event bus service's `emit` method in the service's methods to emit an event:
214
215 export const serviceHighlights = [
216 ["6", "emit", "Emit an event."],
217 ["7", "name", "The name of the event to emit."],
218 ["8", "data", "The data payload to pass with the event."]
219 ]
220
221 ```ts title="src/modules/blog/service.ts" highlights={serviceHighlights}
222 class BlogModuleService {
223 // ...
224 performAction() {
225 // TODO perform action
226
227 this.eventBusService_.emit({
228 name: "custom.event",
229 data: {
230 id: "123",
231 // other data payload
232 },
233 })
234 }
235 }
236 ```
237
238 The method accepts an object having the following properties:
239
240 - `name`: The event's name.
241 - `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
242
243 ### Test it Out
244
245 If you execute the `performAction` method of your service, the event is emitted and you can see it in your application's logs.
246
247 Any subscribers listening to the event are also executed.