on GitHub" data-tooltip-id=":R1blcldtb:">v2.5.1·Edited Nov 25·
In this chapter, you'll learn about event types and how to emit an event in a service or workflow.
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.
There are two types of events in Medusa:
order.placed
event after a cart is completed.Workflow events are the most common event type in development, as most custom features and customizations are built around workflows.
Some examples of workflow events:
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.
Some examples of service events:
To emit a workflow event, use the emitEventStep
helper step provided in the @medusajs/medusa/core-flows
package.
For example:
1import { 2 createWorkflow,3} from "@medusajs/framework/workflows-sdk"4import {5 emitEventStep,6} from "@medusajs/medusa/core-flows"7 8const helloWorldWorkflow = createWorkflow(9 "hello-world",10 () => {11 // ...12 13 emitEventStep({14 eventName: "custom.created",15 data: {16 id: "123",17 // other data payload18 },19 })20 }21)
The emitEventStep
accepts an object having the following properties:
eventName
: The event's name.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.In this example, you emit the event custom.created
and pass in the data payload an ID property.
If you execute the workflow, the event is emitted and you can see it in your application's logs.
Any subscribers listening to the event are executed.
To emit a service event:
event_bus
from the module's container in your service's constructor:emit
method in the service's methods to emit an event:The method accepts an object having the following properties:
name
: The event's name.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.medusa-config.ts
in the dependencies
property:The dependencies
property accepts an array of module registration keys. The specified modules' main services are injected into the module's container.
That's how you can resolve it in your module's main service's constructor.
If you execute the performAction
method of your service, the event is emitted and you can see it in your application's logs.
Any subscribers listening to the event are also executed.