|
1
|
# Custom Module |
|
2
|
|
|
3
|
A module is a package of reusable functionalities. It can be integrated into your Medusa application without affecting the overall system. |
|
4
|
|
|
5
|
To create a module: |
|
6
|
|
|
7
|
## 1. Create a Service |
|
8
|
|
|
9
|
A module must define a service. A service is a TypeScript or JavaScript class holding methods related to a business logic or commerce functionality. |
|
10
|
|
|
11
|
For example, create the file `src/modules/hello/service.ts` with the following content: |
|
12
|
|
|
13
|
```ts title="src/modules/hello/service.ts" |
|
14
|
export default class HelloModuleService { |
|
15
|
getMessage() { |
|
16
|
return "Hello, world!" |
|
17
|
} |
|
18
|
} |
|
19
|
``` |
|
20
|
|
|
21
|
## 2. Export Module Definition |
|
22
|
|
|
23
|
A module must have an `index.ts` file in its root directory that exports its definition. The definition specifies the main service of the module. |
|
24
|
|
|
25
|
For example, create the file `src/modules/hello/index.ts` with the following content: |
|
26
|
|
|
27
|
```ts title="src/modules/hello.index.ts" highlights={[["4", "", "The main service of the module."]]} |
|
28
|
import HelloModuleService from "./service" |
|
29
|
import { Module } from "@medusajs/framework/utils" |
|
30
|
|
|
31
|
export const HELLO_MODULE = "hello" |
|
32
|
|
|
33
|
export default Module(HELLO_MODULE, { |
|
34
|
service: HelloModuleService, |
|
35
|
}) |
|
36
|
``` |
|
37
|
|
|
38
|
## 3. Add Module to Configurations |
|
39
|
|
|
40
|
The last step is to add the module in Medusa’s configurations. |
|
41
|
|
|
42
|
In `medusa-config.js`, add the module to the `modules` object: |
|
43
|
|
|
44
|
```js title="medusa-config.js" |
|
45
|
import { HELLO_MODULE } from "./src/modules/hello" |
|
46
|
|
|
47
|
module.exports = defineConfig({ |
|
48
|
// ... |
|
49
|
modules: [ |
|
50
|
{ |
|
51
|
resolve: "./modules/hello", |
|
52
|
} |
|
53
|
] |
|
54
|
}) |
|
55
|
``` |
|
56
|
|
|
57
|
## Use Module |
|
58
|
|
|
59
|
You can resolve the main service of the module in other resources, such as an API route: |
|
60
|
|
|
61
|
```ts |
|
62
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework" |
|
63
|
import HelloModuleService from "../../../modules/hello/service" |
|
64
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
65
|
|
|
66
|
export async function GET( |
|
67
|
req: MedusaRequest, |
|
68
|
res: MedusaResponse |
|
69
|
): Promise<void> { |
|
70
|
const helloModuleService: HelloModuleService = req.scope.resolve( |
|
71
|
HELLO_MODULE |
|
72
|
) |
|
73
|
|
|
74
|
res.json({ |
|
75
|
message: helloModuleService.getMessage(), |
|
76
|
}) |
|
77
|
} |
|
78
|
``` |