|
1
|
# Custom subscribers |
|
2
|
|
|
3
|
Subscribers handle events emitted in the Medusa application. |
|
4
|
|
|
5
|
The subscriber is created in a TypeScript or JavaScript file under the `src/subscribers` directory. |
|
6
|
|
|
7
|
For example, create the file `src/subscribers/product-created.ts` with the following content: |
|
8
|
|
|
9
|
```ts |
|
10
|
import { |
|
11
|
type SubscriberConfig, |
|
12
|
} from "@medusajs/framework" |
|
13
|
|
|
14
|
// subscriber function |
|
15
|
export default async function productCreateHandler() { |
|
16
|
console.log("A product was created") |
|
17
|
} |
|
18
|
|
|
19
|
// subscriber config |
|
20
|
export const config: SubscriberConfig = { |
|
21
|
event: "product.created", |
|
22
|
} |
|
23
|
``` |
|
24
|
|
|
25
|
A subscriber file must export: |
|
26
|
|
|
27
|
- The subscriber function that is an asynchronous function executed whenever the associated event is triggered. |
|
28
|
- A configuration object defining the event this subscriber is listening to. |
|
29
|
|
|
30
|
## Subscriber Parameters |
|
31
|
|
|
32
|
A subscriber receives an object having the following properties: |
|
33
|
|
|
34
|
- `event`: An object holding the event's details. It has a `data` property, which is the event's data payload. |
|
35
|
- `container`: The Medusa container. Use it to resolve modules' main services and other registered resources. |
|
36
|
|
|
37
|
```ts |
|
38
|
import type { |
|
39
|
SubscriberArgs, |
|
40
|
SubscriberConfig, |
|
41
|
} from "@medusajs/framework" |
|
42
|
|
|
43
|
export default async function productCreateHandler({ |
|
44
|
event: { data }, |
|
45
|
container, |
|
46
|
}: SubscriberArgs<{ id: string }>) { |
|
47
|
const productId = data.id |
|
48
|
|
|
49
|
const productModuleService = container.resolve("product") |
|
50
|
|
|
51
|
const product = await productModuleService.retrieveProduct(productId) |
|
52
|
|
|
53
|
console.log(`The product ${product.title} was created`) |
|
54
|
} |
|
55
|
|
|
56
|
export const config: SubscriberConfig = { |
|
57
|
event: "product.created", |
|
58
|
} |
|
59
|
``` |