1 ---
2 sidebar_label: "Create Event Module"
3 tags:
4 - event
5 - how to
6 - server
7 ---
8
9 import { TypeList } from "docs-ui"
10
11 export const metadata = {
12 title: `How to Create an Event Module`,
13 }
14
15 # {metadata.title}
16
17 In this guide, you’ll learn how to create an Event Module.
18
19 ## 1. Create Module Directory
20
21 Start by creating a new directory for your module. For example, `src/modules/my-event`.
22
23 ---
24
25 ## 2. Create the Event Service
26
27 Create the file `src/modules/my-event/service.ts` that holds the implementation of the event service.
28
29 The Event Module's main service must extend the `AbstractEventBusModuleService` class from the Medusa Framework:
30
31 ```ts title="src/modules/my-event/service.ts"
32 import {
33 AbstractEventBusModuleService,
34 MedusaError,
35 } from "@medusajs/framework/utils"
36 import { Message } from "@medusajs/framework/types"
37
38 class MyEventService extends AbstractEventBusModuleService {
39 async emit<T>(data: Message<T> | Message<T>[], options: Record<string, unknown>): Promise<void> {
40 throw new MedusaError(
41 MedusaError.Types.UNEXPECTED_STATE,
42 "Method not implemented."
43 )
44 }
45 async releaseGroupedEvents(eventGroupId: string): Promise<void> {
46 throw new MedusaError(
47 MedusaError.Types.UNEXPECTED_STATE,
48 "Method not implemented."
49 )
50 }
51 async clearGroupedEvents(eventGroupId: string): Promise<void> {
52 throw new MedusaError(
53 MedusaError.Types.UNEXPECTED_STATE,
54 "Method not implemented."
55 )
56 }
57 }
58
59 export default MyEventService
60 ```
61
62 The service implements the required methods based on the desired publish/subscribe logic.
63
64 ### eventToSubscribersMap_ Property
65
66 The `AbstractEventBusModuleService` has a field `eventToSubscribersMap_`, which is a JavaScript Map. The map's keys are the event names, whereas the value of each key is an array of subscribed handler functions.
67
68 In your custom implementation, you can use this property to manage the subscribed handler functions:
69
70 ```ts
71 const eventSubscribers =
72 this.eventToSubscribersMap_.get(eventName) || []
73 ```
74
75 ### emit Method
76
77 The `emit` method is used to push an event from the Medusa application into your messaging system. The subscribers to that event would then pick up the message and execute their asynchronous tasks.
78
79 An example implementation:
80
81 ```ts title="src/modules/my-event/service.ts"
82 class MyEventService extends AbstractEventBusModuleService {
83 async emit<T>(data: Message<T> | Message<T>[], options: Record<string, unknown>): Promise<void> {
84 const events = Array.isArray(data) ? data : [data]
85
86 for (const event of events) {
87 console.log(`Received the event ${event.name} with data ${event.data}`)
88
89 // TODO push the event somewhere
90 }
91 }
92 // ...
93 }
94 ```
95
96 The `emit` method receives the following parameters:
97
98 <TypeList
99 types={[
100 {
101 name: "data",
102 type: "`object or array of objects`",
103 description: "The emitted event(s).",
104 optional: false,
105 children: [
106 {
107 name: "name",
108 type: "`string`",
109 description: "The name of the emitted event.",
110 optional: false
111 },
112 {
113 name: "data",
114 type: "`object`",
115 description: "The data payload of the event.",
116 optional: false
117 },
118 {
119 name: "metadata",
120 type: "`object`",
121 description: "Additional details of the emitted event.",
122 optional: false,
123 children: [
124 {
125 name: "eventGroupId",
126 type: "string",
127 description: "A group ID that the event belongs to.",
128 optional: true
129 }
130 ]
131 },
132 {
133 name: "options",
134 type: "`object`",
135 description: "Additional options relevant for the event service.",
136 optional: false
137 }
138 ]
139 }
140 ]}
141 />
142
143 ### releaseGroupedEvents Method
144
145 Grouped events are useful when you have distributed transactions where you need to explicitly group, release, and clear events upon lifecycle transaction events.
146
147 If your Event Module supports grouped events, this method is used to emit all events in a group, then clear that group.
148
149 For example:
150
151 ```ts title="src/modules/my-event/service.ts"
152 class MyEventService extends AbstractEventBusModuleService {
153 protected groupedEventsMap_: Map<string, Message[]>
154
155 constructor() {
156 // @ts-ignore
157 super(...arguments)
158
159 this.groupedEventsMap_ = new Map()
160 }
161
162 async releaseGroupedEvents(eventGroupId: string): Promise<void> {
163 const groupedEvents = this.groupedEventsMap_.get(eventGroupId) || []
164
165 for (const event of groupedEvents) {
166 const { options, ...eventBody } = event
167
168 // TODO emit event
169 }
170
171 await this.clearGroupedEvents(eventGroupId)
172 }
173
174 // ...
175 }
176 ```
177
178 The `releaseGroupedEvents` receives the group ID as a parameter.
179
180 In the example above, you add a `groupedEventsMap_` property to store grouped events. Then, in the method, you emit the events in the group, then clear the grouped events using the `clearGroupedEvents` which you'll learn about next.
181
182 To add events to the grouped events map, you can do it in the `emit` method:
183
184 ```ts title="src/modules/my-event/service.ts"
185 class MyEventService extends AbstractEventBusModuleService {
186 // ...
187 async emit<T>(data: Message<T> | Message<T>[], options: Record<string, unknown>): Promise<void> {
188 const events = Array.isArray(data) ? data : [data]
189
190 for (const event of events) {
191 console.log(`Received the event ${event.name} with data ${event.data}`)
192
193 if (event.metadata.eventGroupId) {
194 const groupedEvents = this.groupedEventsMap_.get(
195 event.metadata.eventGroupId
196 ) || []
197
198 groupedEvents.push(event)
199
200 this.groupedEventsMap_.set(event.metadata.eventGroupId, groupedEvents)
201 continue
202 }
203
204 // TODO push the event somewhere
205 }
206 }
207 }
208 ```
209
210 ### clearGroupedEvents Method
211
212 If your Event Module supports grouped events, this method is used to remove the events of a group.
213
214 For example:
215
216 ```ts title="src/modules/my-event/service.ts"
217 class MyEventService extends AbstractEventBusModuleService {
218 // from previous section
219 protected groupedEventsMap_: Map<string, Message[]>
220
221 async clearGroupedEvents(eventGroupId: string): Promise<void> {
222 this.groupedEventsMap_.delete(eventGroupId)
223 }
224
225 // ...
226 }
227 ```
228
229 The method accepts the group's name as a parameter.
230
231 In the method, you delete the group from the `groupedEventsMap_` property (added in the previous section), deleting the stored events of it as well.
232
233 ---
234
235 ## 3. Create Module Definition File
236
237 Create the file `src/modules/my-event/index.ts` with the following content:
238
239 ```ts title="src/modules/my-event/index.ts"
240 import MyEventService from "./service"
241 import { Module } from "@medusajs/framework/utils"
242
243 export default Module("my_event", {
244 service: MyEventService,
245 })
246 ```
247
248 This exports the module's definition, indicating that the `MyEventService` is the main service of the module.
249
250 ---
251
252 ## 4. Use Module
253
254 To use your Event Module, add it to the `modules` object exported as part of the configurations in `medusa-config.ts`. An Event Module is added under the `eventBus` key.
255
256 For example:
257
258 ```ts title="medusa-config.ts"
259 import { Modules } from "@medusajs/framework/utils"
260
261 // ...
262
263 module.exports = defineConfig({
264 // ...
265 modules: [
266 {
267 resolve: "./src/modules/my-event",
268 options: {
269 // any options
270 },
271 },
272 ],
273 })
274 ```