1 export const metadata = {
2 title: `${pageNumber} Module Isolation`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn how modules are isolated, and what that means for your custom development.
8
9 <Note title="Summary">
10
11 - Modules can't access resources, such as services or data models, from other modules.
12 - Use [Module Links](../../../fundamentals/module-links/page.mdx) to extend an existing module's data models, and [Query](../../query/page.mdx) to retrieve data across modules.
13 - Use [workflows](../../workflows/page.mdx) to build features that depend on functionalities from different modules.
14
15 </Note>
16
17 ## How are Modules Isolated?
18
19 A module is unaware of any resources other than its own, such as services or data models. This means it can't access these resources if they're implemented in another module.
20
21 For example, your custom module can't resolve the Product Module's main service or have direct relationships from its data model to the Product Module's data models.
22
23 A module has its own container, as explained in the [Module Container](../container/page.mdx) chapter. This container includes the module's resources, such as services and data models, and some Framework resources that the Medusa application provides.
24
25 <Note>
26
27 Refer to the [Module Container Resources](!resources!/medusa-container-resources) for a list of resources registered in a module's container.
28
29 </Note>
30
31 ---
32
33 ## Why are Modules Isolated
34
35 Some of the module isolation's benefits include:
36
37 - Integrate your module into any Medusa application without side-effects to your setup.
38 - Replace existing modules with your custom implementation if your use case is drastically different.
39 - Use modules in other environments, such as Edge functions and Next.js apps.
40
41 ---
42
43 ## How to Extend Data Model of Another Module?
44
45 To extend the data model of another module, such as the `Product` data model of the Product Module, use [Module Links](../../../fundamentals/module-links/page.mdx). Module Links allow you to build associations between data models of different modules without breaking the module isolation.
46
47 Then, you can retrieve data across modules using [Query](../../query/page.mdx).
48
49 ---
50
51 ## How to Use Services of Other Modules?
52
53 You'll often build feature that uses functionalities from different modules. For example, if you may need to retrieve brands, then sync them to a third-party service.
54
55 To build functionalities spanning across modules and systems, create a [workflow](../../workflows/page.mdx) whose steps resolve the modules' services to perform these functionalities.
56
57 Workflows ensure data consistency through their roll-back mechanism and tracking of each execution's status, steps, input, and output.
58
59 ### Example
60
61 For example, consider you have two modules:
62
63 1. A module that stores and manages brands in your application.
64 2. A module that integrates a third-party Content Management System (CMS).
65
66 To sync brands from your application to the third-party system, create the following steps:
67
68 export const stepsHighlights = [
69 ["1", "retrieveBrandsStep", "A step that retrieves brands using a brand module."],
70 ["14", "createBrandsInCmsStep", "A step that creates brands using a CMS module."],
71 ["25", "", "Add a compensation function to the step if an error occurs."]
72 ]
73
74 ```ts title="Example Steps" highlights={stepsHighlights}
75 const retrieveBrandsStep = createStep(
76 "retrieve-brands",
77 async (_, { container }) => {
78 const brandModuleService = container.resolve(
79 "brand"
80 )
81
82 const brands = await brandModuleService.listBrands()
83
84 return new StepResponse(brands)
85 }
86 )
87
88 const createBrandsInCmsStep = createStep(
89 "create-brands-in-cms",
90 async ({ brands }, { container }) => {
91 const cmsModuleService = container.resolve(
92 "cms"
93 )
94
95 const cmsBrands = await cmsModuleService.createBrands(brands)
96
97 return new StepResponse(cmsBrands, cmsBrands)
98 },
99 async (brands, { container }) => {
100 const cmsModuleService = container.resolve(
101 "cms"
102 )
103
104 await cmsModuleService.deleteBrands(
105 brands.map((brand) => brand.id)
106 )
107 }
108 )
109 ```
110
111 The `retrieveBrandsStep` retrieves the brands from a Brand Module, and the `createBrandsInCmsStep` creates the brands in a third-party system using a CMS Module.
112
113 Then, create the following workflow that uses these steps:
114
115 ```ts title="Example Workflow"
116 export const syncBrandsWorkflow = createWorkflow(
117 "sync-brands",
118 () => {
119 const brands = retrieveBrandsStep()
120
121 createBrandsInCmsStep({ brands })
122 }
123 )
124 ```
125
126 You can then use this workflow in an API route, scheduled job, or other resources that use this functionality.
127
128 ---
129
130 ## How to Use Framework APIs and Tools in Module?
131
132 ### Framework Tools in Module Container
133
134 A module has in its container some Framework APIs and tools, such as [Logger](../../../debugging-and-testing/logging/page.mdx). You can refer to the [Module Container Resources](!resources!/medusa-container-resources) for a list of resources registered in a module's container.
135
136 You can resolve those resources in the module's services and loaders.
137
138 For example:
139
140 ```ts title="Example Service"
141 import { Logger } from "@medusajs/framework/types"
142
143 type InjectedDependencies = {
144 logger: Logger
145 }
146
147 export default class BlogModuleService {
148 protected logger_: Logger
149
150 constructor({ logger }: InjectedDependencies) {
151 this.logger_ = logger
152
153 this.logger_.info("[BlogModuleService]: Hello World!")
154 }
155
156 // ...
157 }
158 ```
159
160 In this example, the `BlogModuleService` class resolves the `Logger` service from the module's container and uses it to log a message.
161
162 ### Using Framework Tools in Workflows
163
164 Some Framework APIs and tools are not registered in the module's container. For example, [Query](../../query/page.mdx) is only registered in the Medusa container.
165
166 You should, instead, build workflows that use these APIs and tools along with your module's service.
167
168 For example, you can create a workflow that retrieves data using Query, then pass the data to your module's service to perform some action.
169
170 ```ts title="Example Workflow"
171 import {
172 createWorkflow,
173 createStep,
174 StepResponse,
175 } from "@medusajs/framework/workflows-sdk"
176 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
177
178 const createBrandsInCmsStep = createStep(
179 "create-brands-in-cms",
180 async ({ brands }, { container }) => {
181 const cmsModuleService = container.resolve(
182 "cms"
183 )
184
185 const cmsBrands = await cmsModuleService.createBrands(brands)
186
187 return new StepResponse(cmsBrands, cmsBrands)
188 },
189 async (brands, { container }) => {
190 const cmsModuleService = container.resolve(
191 "cms"
192 )
193
194 await cmsModuleService.deleteBrands(
195 brands.map((brand) => brand.id)
196 )
197 }
198 )
199
200 const syncBrandsWorkflow = createWorkflow(
201 "sync-brands",
202 () => {
203 const { data: brands } = useQueryGraphStep({
204 entity: "brand",
205 fields: [
206 "*",
207 "products.*",
208 ],
209 })
210
211 createBrandsInCmsStep({ brands })
212 }
213 )
214 ```
215
216 In this example, you use the `useQueryGraphStep` to retrieve brands with their products, then pass the brands to the `createBrandsInCmsStep` step.
217
218 In the `createBrandsInCmsStep`, you resolve the CMS Module's service from the module's container and use it to create the brands in the third-party system. You pass the brands you retrieved using Query to the module's service.
219
220 ### Injecting Dependencies to Module
221
222 Some cases still require you to access external resources, mainly [Infrastructure Modules](!resources!/infrastructure-modules) or Framework tools, in your module.
223
224 <Note>
225
226 The following services are available in every module's container by default, without any `dependencies` declaration: `logger`, `event_bus`, `manager`, `configModule`, and `pgConnection`. Refer to the [Module Container Resources](!resources!/medusa-container-resources) for the full list.
227
228 </Note>
229
230 For other Infrastructure Modules not in the default set, you can inject them into your module's service in `medusa-config.ts` using the `dependencies` property of the module's configuration.
231
232 <Note type="warning">
233
234 Use this approach only when absolutely necessary, where workflows aren't sufficient for your use case. By injecting dependencies, you risk breaking your module if the dependency isn't provided, or if the dependency's API changes.
235
236 </Note>
237
238 For example, to inject the Analytics Module:
239
240 ```ts title="medusa-config.ts"
241 import { Modules } from "@medusajs/framework/utils"
242
243 module.exports = defineConfig({
244 // ...
245 modules: [
246 {
247 resolve: "./src/modules/blog",
248 dependencies: [
249 Modules.ANALYTICS,
250 ],
251 },
252 ],
253 })
254 ```
255
256 In this example, you inject the Analytics Module's service into your module's container.
257
258 <Note>
259
260 Only the main service will be injected into the module's container.
261
262 </Note>
263
264 You can then use the Analytics Module's service in your module's service:
265
266 ```ts title="Example Service"
267 import { AbstractAnalyticsProviderService } from "@medusajs/framework/utils"
268
269 class BlogModuleService {
270 protected analyticsService_: AbstractAnalyticsProviderService
271
272 constructor({ analytics }) {
273 this.analyticsService_ = analytics
274 }
275
276 performAction() {
277 // TODO perform action
278
279 this.analyticsService_.identify({
280 actor_id: "123",
281 properties: {
282 name: "John Doe",
283 },
284 })
285 }
286 }
287 ```