api-ref: custom API reference (#4770)

* initialized next.js project

* finished markdown sections

* added operation schema component

* change page metadata

* eslint fixes

* fixes related to deployment

* added response schema

* resolve max stack issue

* support for different property types

* added support for property types

* added loading for components

* added more loading

* type fixes

* added oneOf type

* removed console

* fix replace with push

* refactored everything

* use static content for description

* fixes and improvements

* added code examples section

* fix path name

* optimizations

* fixed tag navigation

* add support for admin and store references

* general enhancements

* optimizations and fixes

* fixes and enhancements

* added search bar

* loading enhancements

* added loading

* added code blocks

* added margin top

* add empty response text

* fixed oneOf parameters

* added path and query parameters

* general fixes

* added base path env variable

* small fix for arrays

* enhancements

* design enhancements

* general enhancements

* fix isRequired

* added enum values

* enhancements

* general fixes

* general fixes

* changed oas generation script

* additions to the introduction section

* added copy button for code + other enhancements

* fix response code block

* fix metadata

* formatted store introduction

* move sidebar logic to Tags component

* added test env variables

* fix code block bug

* added loading animation

* added expand param + loading

* enhance operation loading

* made responsive + improvements

* added loading provider

* fixed loading

* adjustments for small devices

* added sidebar label for endpoints

* added feedback component

* fixed analytics

* general fixes

* listen to scroll for other headings

* added sample env file

* update api ref files + support new fields

* fix for external docs link

* added new sections

* fix last item in sidebar not showing

* move docs content to www/docs

* change redirect url

* revert change

* resolve build errors

* configure rewrites

* changed to environment variable url

* revert changing environment variable name

* add environment variable for API path

* fix links

* fix tailwind settings

* remove vercel file

* reconfigured api route

* move api page under api

* fix page metadata

* fix external link in navigation bar

* update api spec

* updated api specs

* fixed google lint error

* add max-height on request samples

* add padding before loading

* fix for one of name

* fix undefined types

* general fixes

* remove response schema example

* redesigned navigation bar

* redesigned sidebar

* fixed up paddings

* added feedback component + report issue

* fixed up typography, padding, and general styling

* redesigned code blocks

* optimization

* added error timeout

* fixes

* added indexing with algolia + fixes

* fix errors with algolia script

* redesign operation sections

* fix heading scroll

* design fixes

* fix padding

* fix padding + scroll issues

* fix scroll issues

* improve scroll performance

* fixes for safari

* optimization and fixes

* fixes to docs + details animation

* padding fixes for code block

* added tab animation

* fixed incorrect link

* added selection styling

* fix lint errors

* redesigned details component

* added detailed feedback form

* api reference fixes

* fix tabs

* upgrade + fixes

* updated documentation links

* optimizations to sidebar items

* fix spacing in sidebar item

* optimizations and fixes

* fix endpoint path styling

* remove margin

* final fixes

* change margin on small devices

* generated OAS

* fixes for mobile

* added feedback modal

* optimize dark mode button

* fixed color mode useeffect

* minimize dom size

* use new style system

* radius and spacing design system

* design fixes

* fix eslint errors

* added meta files

* change cron schedule

* fix docusaurus configurations

* added operating system to feedback data

* change content directory name

* fixes to contribution guidelines

* revert renaming content

* added api-reference to documentation workflow

* fixes for search

* added dark mode + fixes

* oas fixes

* handle bugs

* added code examples for clients

* changed tooltip text

* change authentication to card

* change page title based on selected section

* redesigned mobile navbar

* fix icon colors

* fix key colors

* fix medusa-js installation command

* change external regex in algolia

* change changeset

* fix padding on mobile

* fix hydration error

* update depedencies
This commit is contained in:
Shahed Nasser
2023-08-15 18:07:54 +03:00
committed by GitHub
parent 16249ec280
commit 914d773d3a
3270 changed files with 22075 additions and 192064 deletions
@@ -0,0 +1,260 @@
---
description: 'In this document, youll learn how to create an events module, then test and publish the module as an NPM package.'
addHowToData: true
---
# Create Events Module
In this document, youll learn how to create an events module.
## Overview
Medusa provides ready-made modules for events, including the local and Redis modules. If you prefer another technology used for managing events, you can build a module locally and use it in your Medusa backend. You can also publish to NPM and reuse it across multiple Medusa backend instances.
In this document, youll learn how to build your own Medusa events module, mainly focusing on creating the event bus service and the available methods you need to implement within your module.
---
## (Optional) Step 0: Prepare Module Directory
Before you start implementing your module, it's recommended to prepare the directory or project holding your custom implementation.
You can refer to the [Project Preparation step in the Create Module documentation](../modules/create.mdx#optional-step-0-project-preparation) to learn how to do that.
---
## Step 1: Create the Service
Create the file `services/event-bus-custom.ts` which will hold your event bus service. Note that the name of the file is recommended to be in the format `event-bus-<service_name>` where `<service_name>` is the name of the service youre integrating. For example, `event-bus-redis`.
Add the following content to the file:
```ts title=services/event-bus-custom.ts
import { EmitData, EventBusTypes } from "@medusajs/types"
import { AbstractEventBusModuleService } from "@medusajs/utils"
class CustomEventBus extends AbstractEventBusModuleService {
async emit<T>(
eventName: string,
data: T,
options: Record<string, unknown>
): Promise<void>;
async emit<T>(data: EmitData<T>[]): Promise<void>;
async emit(
eventName: unknown,
data?: unknown,
options?: unknown
): Promise<void> {
throw new Error("Method not implemented.")
}
}
export default CustomEventBus
```
This creates the class `CustomEventBus` that implements the `AbstractEventBusModuleService` class imported from `@medusajs/utils`. Feel free to rename the class to whats relevant for your event bus service.
In the class you must implement the `emit` method. You can optionally implement the `subscribe` and `unsubscribe` methods.
---
## Step 2: Implement Methods
### Note About the eventToSubscribersMap Property
The `AbstractEventBusModuleService` implements two methods for handling subscription: `subscribe` and `unsubscribe`. In these methods, the subscribed handler methods are managed within a class property `eventToSubscribersMap`, which is a JavaScript Map. They map keys are the event names, whereas the value of each key is an array of subscribed handler methods.
In your custom implementation, you can use this property to manage the subscribed handler methods. For example, you can get the subscribers of a method using the `get` method of the map:
```ts
const eventSubscribers =
this.eventToSubscribersMap.get(eventName) || []
```
Alternatively, you can implement custom logic for the `subscribe` and `unsubscribe` events, which is explained later in this guide.
### constructor
The `constructor` method of a service allows you to prepare any third-party client or service necessary to be used in other methods. It also allows you to get access to the modules options which are typically defined in `medusa-config.js`, and to other services and resources in the Medusa backend using [dependency injection](../fundamentals/dependency-injection.md).
Heres an example of how you can use the `constructor` to store the options of your module:
<!-- eslint-disable prefer-rest-params -->
```ts title=services/event-bus-custom.ts
class CustomEventBus extends AbstractEventBusModuleService {
protected readonly moduleOptions: Record<string, any>
constructor({
// inject resources from the Medusa backend
// for example, you can inject the logger
logger,
}, options) {
super(...arguments)
this.moduleOptions = options
}
// ...
}
```
### emit
The `emit` method is used to push an event from Medusa into your messaging system. Typically, the subscribers to that event would then pick up the message and execute their asynchronous tasks.
The `emit` method has two different signatures:
1. The first signature accepts three parameters. The first parameter is `eventName` being a required string indicating the name of the event to trigger. The second parameter is `data` being the optional data to send to subscribers of that event. The third optional parameter `options` which can be used to pass options specific to the event bus.
2. The second signature accepts one parameter, which is an array of objects having three properties: `eventName`, `data`, and `options`. These are the same as the parameters that can be passed in the first signature. This signature allows emitting more than one event.
The `options` parameter depends on the event bus integrating. For example, the Redis event bus accept the following options:
```ts title=services/event-bus-custom.ts
type JobData<T> = {
eventName: string
data: T
completedSubscriberIds?: string[] | undefined
}
```
You can implement your method in a way that supports both signatures by checking the type of the first input. For example:
```ts title=services/event-bus-custom.ts
class CustomEventBus extends AbstractEventBusModuleService {
// ...
async emit<T>(
eventName: string,
data: T,
options: Record<string, unknown>
): Promise<void>;
async emit<T>(data: EmitData<T>[]): Promise<void>;
async emit<T>(
eventOrData: string | EmitData<T>[],
data?: T,
options: Record<string, unknown> = {}
): Promise<void> {
const isBulkEmit = Array.isArray(eventOrData)
// emit event
}
}
```
### (optional) subscribe
As mentioned earlier, this method is already implemented in the `AbstractEventBusModuleService` class. This section explains how you can implement your custom subscribe logic if necessary.
The `subscribe` method attaches a handler method to the specified event, which is run when the event is triggered. It is typically used inside a subscriber class.
The `subscribe` method accepts three parameters:
1. The first parameter `eventName` is a required string. It indicates which event the handler method is subscribing to.
2. The second parameter `subscriber` is a required function that performs an action when the event is triggered.
3. The third parameter `context` is an optional object that has the property `subscriberId`. Subscriber IDs are useful to differentiate between handler methods when retrying a failed method. Its also useful for unsubscribing an event handler. Note that if you must implement the mechanism around assigning IDs to subscribers when you override the `subscribe` method.
The implementation of this method depends on the service youre using for the event bus:
```ts title=services/event-bus-custom.ts
class CustomEventBus extends AbstractEventBusModuleService {
// ...
subscribe(
eventName: string | symbol,
subscriber: EventBusTypes.Subscriber,
context?: EventBusTypes.SubscriberContext): this {
// TODO implement subscription
}
}
```
### (optional) unsubscribe
As mentioned earlier, this method is already implemented in the `AbstractEventBusModuleService` class. This section explains how you can implement your custom unsubscribe logic if necessary.
The `unsubscribe` method is used to unsubscribe a handler method from an event.
The `unsubscribe` method accepts three parameters:
1. The first parameter `eventName` is a required string. It indicates which event the handler method is unsubscribing from.
2. The second parameter `subscriber` is a required function that was initially subscribed to the event.
3. The third parameter `context` is an optional object that has the property `subscriberId`. It can be used to specify the ID of the subscriber to unsubscribe.
The implementation of this method depends on the service youre using for the event bus:
```ts title=services/event-bus-custom.ts
class CustomEventBus extends AbstractEventBusModuleService {
// ...
unsubscribe(
eventName: string | symbol,
subscriber: EventBusTypes.Subscriber,
context?: EventBusTypes.SubscriberContext): this {
// TODO implement subscription
}
}
```
---
## Step 3: Export the Service
After implementing the event bus service, you must export it so that the Medusa backend can use it.
Create the file `index.ts` with the following content:
```ts title=services/event-bus-custom.ts
import { ModuleExports } from "@medusajs/modules-sdk"
import { CustomEventBus } from "./services"
const service = CustomEventBus
const moduleDefinition: ModuleExports = {
service,
}
export default moduleDefinition
```
This exports a module definition, which requires at least a `service`. If you named your service something other than `CustomEventBus`, make sure to replace it with that.
You can learn more about what other properties you can export in your module definition in the [Create a Module documentation](../modules/create.mdx#step-2-export-module).
---
## Step 4: Test your Module
You can test your module in the Medusa backend by referencing it in the configurations.
To do that, add the module to the exported configuration in `medusa-config.js` as follows:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
cacheService: {
resolve: "path/to/custom-module",
options: {
// any necessary options
},
},
},
}
```
Make sure to replace the `path/to/custom-module` with a relative path from your Medusa backend to your module. You can learn more about module reference in the [Create Module documentation](../modules/create.mdx#module-reference).
You can also add any necessary options to the module.
Then, to test the module, run the Medusa backend which also runs your module:
```bash npm2yarn
npx medusa develop
```
---
## (Optional) Step 5: Publish your Module
You can publish your events module to NPM. This can be useful if you want to reuse your module across Medusa backend instances, or want to allow other developers to use it.
You can refer to the [Publish Module documentation](../modules/publish.md) to learn how to publish your module.
@@ -0,0 +1,134 @@
---
description: 'Learn how to create a subscriber in Medusa. You can use subscribers to implement functionalities like sending an order confirmation email.'
addHowToData: true
---
# How to Create a Subscriber
In this document, youll learn how to create a [Subscriber](./subscribers.mdx) in Medusa that listens to events to perform an action.
## Implementation
A subscriber is a TypeScript or JavaScript file that is created under `src/subscribers`. Its file name, by convention, should be the class name of the subscriber without the word `Subscriber`. For example, if the subscriber is `HelloSubscriber`, the file name should be `hello.ts`.
After creating the file under `src/subscribers`, in the constructor of your subscriber, listen to events using `eventBusService.subscribe` , where `eventBusService` is a service injected into your subscribers constructor.
The `eventBusService.subscribe` method receives the name of the event as a first parameter and as a second parameter a method in your subscriber that will handle this event.
For example, here is the `OrderNotifierSubscriber` class created in `src/subscribers/order-notifier.ts`:
```ts title=src/subscribers/order-notifier.ts
class OrderNotifierSubscriber {
constructor({ eventBusService }) {
eventBusService.subscribe("order.placed", this.handleOrder)
}
handleOrder = async (data) => {
console.log("New Order: " + data.id)
}
}
export default OrderNotifierSubscriber
```
This subscriber registers the method `handleOrder` as one of the handlers of the `order.placed` event. The method `handleOrder` will be executed every time an order is placed. It receives the order ID in the `data` parameter. You can then use the orders details to perform any kind of task you need.
:::tip
For the `order.placed` event, the `data` object won't contain other order data. Only the ID of the order. You can retrieve the order information using the `orderService`.
:::
### Subscriber ID
The `subscribe` method of the `eventBusService` accepts a third optional parameter which is a context object. This object has a property `subscriberId` with its value being a string. This ID is useful when there is more than one handler method attached to a single event or if you have multiple Medusa backends running. This allows the events bus service to differentiate between handler methods when retrying a failed one.
If a subscriber ID is not passed on subscription, all handler methods are run again. This can lead to data inconsistencies or general unwanted behavior in your system. On the other hand, if you want all handler methods to run again when one of them fails, you can omit passing a subscriber ID.
An example of using the subscribe method with the third parameter:
```ts
eventBusService.subscribe("order.placed", this.handleOrder, {
subscriberId: "my-unique-subscriber",
})
```
---
## Retrieve Medusa Configurations
Within your subscriber, you may need to access the Medusa configuration exported from `medusa-config.js`. To do that, you can access `configModule` using dependency injection.
For example:
```ts
import { ConfigModule, EventBusService } from "@medusajs/medusa"
type InjectedDependencies = {
eventBusService: EventBusService
configModule: ConfigModule
}
class OrderNotifierSubscriber {
protected readonly configModule_: ConfigModule
constructor({
eventBusService,
configModule,
}: InjectedDependencies) {
this.configModule_ = configModule
eventBusService.subscribe("order.placed", this.handleOrder)
}
// ...
}
export default OrderNotifierSubscriber
```
---
## Using Services in Subscribers
You can access any service through the dependencies injected to your subscribers constructor.
For example:
```ts title=src/subscribers/order-notifier.ts
class OrderNotifierSubscriber {
constructor({ productService, eventBusService }) {
this.productService = productService
eventBusService.subscribe(
"order.placed",
this.handleOrder
)
}
// ...
}
```
You can then use `this.productService` anywhere in your subscribers methods. For example:
```ts title=src/subscribers/order-notifier.ts
class OrderNotifierSubscriber {
// ...
handleOrder = async (data) => {
// ...
const product = this.productService.list()
}
}
```
:::note
When using attributes defined in the subscriber, such as the `productService` in the example above, you must use an arrow function to declare the method. Otherwise, the attribute will be undefined when used.
:::
---
## See Also
- [Example: send order confirmation email](../../modules/orders/backend/send-order-confirmation.md)
- [Example: send registration confirmation email](../../modules/customers/backend/send-confirmation.md)
- [Create a Plugin](../plugins/create.mdx)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,131 @@
---
description: 'Learn how the events system is implemented in Medusa. It is built on a publish-subscribe architecture. The Medusa core publishes events when certain actions take place.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Events
In this document, youll learn what events are and why theyre useful in Medusa.
## Overview
Events are used in Medusa to inform different parts of the commerce ecosystem that this event occurred. For example, when an order is placed, the `order.placed` event is triggered, which informs notification services like SendGrid to send a confirmation email to the customer.
:::tip
If you want to implement order confirmation emails, you can check this [step-by-step guide](../../modules/orders/backend/send-order-confirmation.md).
:::
The events system in Medusa is built on a publish/subscribe architecture. The Medusa core publish an event when an action takes place, and modules, plugins, or other forms of customizations can subscribe to that event. [Subscribers](./subscribers.mdx) can then perform a task asynchronously when the event is triggered.
Although the core implements the main logic behind the events system, youll need to use an event module that takes care of the publish/subscribe functionality such as subscribing and emitting events. Medusa provides modules that you can use both for development and production, including Redis and Local modules.
---
## Database Transactions
Transactions in Medusa ensure Atomicity, Consistency, Isolation, and Durability (ACID) guarantees for operations in the Medusa core.
In many cases, services typically update resources in the database and emit an event within a transactional operation. To ensure that these events don't cause data inconsistencies (for example, a plugin subscribes to an event to contact a third-party service, but the transaction fails) the concept of a staged job is introduced.
Instead of events being processed immediately, they're stored in the database as a staged job until they're ready. In other words, until the transaction has succeeded.
This rather complex logic is abstracted away from the consumers of the EventBusService, but here's an example of the flow when an API request is made:
- API request starts.
- Transaction is initiated.
- Service layer performs some logic.
- Events are emitted and stored in the database for eventual processing.
- Transaction is committed.
- API request ends.
- Events in the database become visible.
To pull staged jobs from the database, a separate enqueuer polls the database every three seconds to discover new visible jobs. These jobs are then added to the queue and processed as described in the Processing section earlier.
---
## Emitting Events
You can emit events in Medusa using the `EventBusService`. For example:
```ts
this.eventBusService.emit("custom-event", {
// attach any data to the event
})
```
You can also emit more than one event:
```ts
this.eventBusService.emit([
{
eventName: "custom-event-1",
data: {
// attach any data to the event
},
},
{
eventName: "custom-event-2",
data: {
// attach any data to the event
},
},
])
```
---
## Available Modules
Medusas default starter project comes with the local event module (`@medusajs/event-bus-local`). For production environments, its recommended to use the Redis event module package (`@medusajs/event-bus-redis`) that you can install.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/events/modules/redis',
label: 'Redis',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to install Redis events module in Medusa.'
}
},
{
type: 'link',
href: '/development/events/modules/local',
label: 'Local',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to install local events module in Medusa.'
}
},
]} />
---
## Custom Development
Developers can create custom event modules, allowing them to integrate any third-party services or logic to handle this functionality. Developers can also create and use subscribers to handle events in Medusa.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/events/create-module',
label: 'Create an Event Module',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an event module.'
}
},
{
type: 'link',
href: '/development/events/create-subscriber',
label: 'Create a Subscriber',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a subscriber.'
}
},
]} />
@@ -0,0 +1,68 @@
---
description: 'In this document, youll learn about the local events module and how you can install it in your Medusa backend.'
addHowToData: true
---
# Local Events Module
In this document, youll learn about the local events module and how you can install it in your Medusa backend.
## Overview
Medusas modular architecture allows developers to extend or completely replace the logic used for events. You can create a custom module, or you can use the modules Medusa provides.
One of these modules is the local events module. This module allows you to utilize Node EventEmitter for the events system in Medusa. The Node EventEmitter is limited to a single process environment. This module is useful for development and testing, but its recommended to use the [Redis events module](./redis.md) in production.
This document will you guide you through installing the local events module.
---
## Prerequisites
Its assumed you already have a Medusa backend installed. If not, you can learn how to install it by following [this guide](../../backend/install.mdx).
---
## Step 1: Install the Module
In the root directory of your Medusa backend, install the Redis events module with the following command:
```bash npm2yarn
npm install @medusajs/event-bus-local
```
---
## Step 2: Add Configuration
In `medusa-config.js`, add the following to the exported object:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
eventBus: {
resolve: "@medusajs/event-bus-local",
},
},
}
```
This registers the local events module as the main events service to use. This module does not require any options.
---
## Step 4: Test Module
To test the module, run the following command to start the Medusa backend:
```bash npm2yarn
npx medusa develop
```
If the module was installed successfully, you should see the following message in the logs:
```bash noCopy noReport
Local Event Bus installed. This is not recommended for production.
```
@@ -0,0 +1,95 @@
---
description: 'In this document, youll learn about the Redis events module and how you can install it in your Medusa backend.'
addHowToData: true
---
# Redis Events Module
In this document, youll learn about the Redis events module and how you can install it in your Medusa backend.
## Overview
Medusas modular architecture allows developers to extend or completely replace the logic used for events. You can create a custom module, or you can use the modules Medusa provides.
One of these modules is the Redis module. This module allows you to utilize Redis for the event bus functionality. When installed, the Medusas events system is powered by BullMQ and `io-redis`. BullMQ is responsible for the message queue and worker, and `io-redis` is the underlying Redis client that BullMQ connects to for events storage.
This document will you guide you through installing the Redis module.
---
## Prerequisites
### Medusa Backend
Its assumed you already have a Medusa backend installed. If not, you can learn how to install it by following [this guide](../../backend/install.mdx).
### Redis
You must have Redis installed and configured in your Medusa backend. You can learn how to install Redis in [their documentation](https://redis.io/docs/getting-started/installation/).
---
## Step 1: Install the Module
In the root directory of your Medusa backend, install the Redis events module with the following command:
```bash npm2yarn
npm install @medusajs/event-bus-redis
```
---
## Step 2: Add Environment Variable
The Redis events module requires a connection URL to Redis as part of its options. If you dont already have an environment variable set for a Redis URL, make sure to add one:
```bash
EVENTS_REDIS_URL=<YOUR_REDIS_URL>
```
Where `<YOUR_REDIS_URL>` is a connection URL to your Redis instance.
---
## Step 3: Add Configuration
In `medusa-config.js`, add the following to the exported object:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
eventBus: {
resolve: "@medusajs/event-bus-redis",
options: {
redisUrl: process.env.EVENTS_REDIS_URL,
},
},
},
}
```
This registers the Redis events module as the main event bus service to use. In the options, you pass `redisUrl` with the value being the environment variable you set. This is the only required option.
Other available options include:
- `queueName`: a string indicating the name of the BullMQ queue. By default, its `events-queue`.
- `queueOptions`: an object containing options for the BullMQ queue. You can learn about available options in [BullMQs documentation](https://api.docs.bullmq.io/interfaces/QueueOptions.html). By default, its an empty object.
- `redisOptions`: an object containing options for the Redis instance. You can learn about available options in [io-rediss documentation](https://luin.github.io/ioredis/index.html#RedisOptions). By default, its an empty object.
---
## Step 4: Test Module
To test the module, run the following command to start the Medusa backend:
```bash npm2yarn
npx medusa develop
```
If the module was installed successfully, you should see the following message in the logs:
```bash noCopy noReport
Connection to Redis in module 'event-bus-redis' established
```
@@ -0,0 +1,45 @@
---
description: 'Learn what subscribers are in Medusa. Subscribers are used to listen to triggered events to perform an action.'
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Subscribers
In this document, you'll learn what Subscribers are in Medusa.
## What are Subscribers
Subscribers register handlers for an events and allows you to perform an action when that event occurs. For example, if you want to send your customer an email when they place an order, then you can listen to the `order.placed` event and send the email when the event is emitted.
Natively in Medusa there are subscribers to handle different events. However, you can also create your own custom subscribers.
Custom subscribers are TypeScript or JavaScript files in your project's `src/subscribers` directory. Files here should export classes, which will be treated as subscribers by Medusa. By convention, the class name should end with `Subscriber` and the file name should be the camel-case version of the class name without `Subscriber`. For example, the `WelcomeSubscriber` class is in the file `src/subscribers/welcome.ts`.
Whenever an event is emitted, the subscribers registered handler method is executed. The handler method receives as a parameter an object that holds data related to the event. For example, if an order is placed the `order.placed` event will be emitted and all the handlers will receive the order id in the parameter object.
### Example Use Cases
Subscribers are useful in many use cases, including:
- Send a confirmation email to the customer when they place an order by subscribing to the `order.placed` event.
- Automatically assign new customers to a customer group by subscribing to the `customer.created`.
- Handle custom events that you emit
---
## Custom Development
Developers can create custom subscribers in the Medusa backend, a plugin, or in a module.
<DocCard item={{
type: 'link',
href: '/development/events/create-subscriber',
label: 'Create a Subscriber',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a subscriber in Medusa.'
}
}}
/>