Raw
1 import { Table } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Read-Only Module Link`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn what a read-only module link is and how to define one.
10
11 ## What is a Read-Only Module Link?
12
13 Consider a scenario where you need to access related records from another module, but don't want the overhead of managing or storing the links between them. This can include cases where you're working with external data models not stored in your Medusa database, such as third-party systems.
14
15 In those cases, instead of defining a [Module Link](../page.mdx) whose linked records must be stored in a link table in the database, you can use a read-only module link. A read-only module link builds a virtual relation from one data model to another in a different module without creating a link table in the database. Instead, the linked record's ID is stored in the first data model's field.
16
17 For example, Medusa creates a read-only module link from the `Cart` data model of the [Cart Module](!resources!/commerce-modules/cart) to the `Customer` data model of the [Customer Module](!resources!/commerce-modules/customer). This link allows you to access the details of the cart's customer without managing the link. Instead, the customer's ID is stored in the `Cart` data model.
18
19 ![Diagram illustrating the read-only module link from cart to customer](https://res.cloudinary.com/dza7lstvk/image/upload/v1742212508/Medusa%20Book/cart-customer_w6vk59.jpg)
20
21 ---
22
23 ## How to Define a Read-Only Module Link
24
25 The `defineLink` function accepts an optional third-parameter object that can hold additional configurations for the module link.
26
27 <Note>
28
29 If you're not familiar with the `defineLink` function, refer to the [Module Links chapter](../page.mdx) for more information.
30
31 </Note>
32
33 To make the module link read-only, pass the `readOnly` property as `true`. You must also set in the link configuration of the first data model a `field` property that specifies the data model's field where the linked record's ID is stored.
34
35 For example:
36
37 export const highlights = [
38 ["8", "field", "The field where the linked record's ID is stored."],
39 ["12", "readOnly", "Set the link as read-only."]
40 ]
41
42 ```ts highlights={highlights}
43 import BlogModule from "../modules/blog"
44 import ProductModule from "@medusajs/medusa/product"
45 import { defineLink } from "@medusajs/framework/utils"
46
47 export default defineLink(
48 {
49 linkable: BlogModule.linkable.post,
50 field: "product_id",
51 },
52 ProductModule.linkable.product,
53 {
54 readOnly: true,
55 }
56 )
57 ```
58
59 In this example, you define a read-only module link from the Blog Module's `post` data model to the Product Module's `product` data model. You do that by:
60
61 - Passing an object as a first parameter that accepts the linkable configuration and the field where the linked record's ID is stored.
62 - Setting the `readOnly` property to `true` in the third parameter.
63
64 Unlike the stored module link, Medusa will not create a table in the database for this link. Instead, Medusa uses the ID stored in the specified field of the first data model to retrieve the linked record.
65
66 ---
67
68 ## Retrieve Read-Only Linked Record
69
70 [Query](../../query/page.mdx) allows you to retrieve records linked through a read-only module link.
71
72 For example, assuming you have the module link created in [the above section](#how-to-define-a-read-only-module-link), you can retrieve a post and its linked product as follows:
73
74 ```ts
75 const { result } = await query.graph({
76 entity: "post",
77 fields: ["id", "product.*"],
78 filters: {
79 id: "post_123",
80 },
81 })
82 ```
83
84 In the above example, you retrieve a post and its linked product. Medusa will use the ID of the product in the post's `product_id` field to determine which product should be retrieved.
85
86 ---
87
88 ## Read-Only Module Link Direction
89
90 A read-only module is uni-directional. So, you can only retrieve the linked record from the first data model. If you need to access the linked record from the second data model, you must define another read-only module link in the opposite direction.
91
92 In the `blog` -> `product` example, you can access a post's product, but you can't access a product's posts. You would have to define another read-only module link from `product` to `blog` to access a product's posts.
93
94 ---
95
96 ## Inverse Read-Only Module Link
97
98 An inverse read-only module link is a read-only module link that allows you to access the linked record based on the ID stored in the second data model.
99
100 For example, consider you want to access a product's posts. You can define a read-only module link from the Product Module's `product` data model to the Blog Module's `post` data model:
101
102 ```ts
103 import BlogModule from "../modules/blog"
104 import ProductModule from "@medusajs/medusa/product"
105 import { defineLink } from "@medusajs/framework/utils"
106
107 export default defineLink(
108 {
109 linkable: ProductModule.linkable.product,
110 field: "id",
111 },
112 {
113 ...BlogModule.linkable.post.id,
114 primaryKey: "product_id",
115 },
116 {
117 readOnly: true,
118 }
119 )
120 ```
121
122 In the above example, you define a read-only module link from the Product Module's `product` data model to the Blog Module's `post` data model. This link allows you to access a product's posts.
123
124 Since you can't add a `post_id` field to the `product` data model, you must:
125
126 1. Set the `field` property in the first data model's link configuration to the product's ID field.
127 2. Spread the `BlogModule.linkable.post.id` object in the second parameter object and set the `primaryKey` property to the field in the `post` data model that holds the product's ID.
128
129 You can now retrieve a product and its linked posts:
130
131 ```ts
132 const { result } = await query.graph({
133 entity: "product",
134 fields: ["id", "post.*"],
135 filters: {
136 id: "prod_123",
137 },
138 })
139 ```
140
141 ---
142
143 ## One-to-One or One-to-Many?
144
145 When you retrieve the linked record through a read-only module link, the retrieved data may be an object (one-to-one) or an array of objects (one-to-many) based on different criteria.
146
147 <Table>
148 <Table.Header>
149 <Table.Row>
150 <Table.HeaderCell>
151 Scenario
152 </Table.HeaderCell>
153 <Table.HeaderCell>
154 Relation Type
155 </Table.HeaderCell>
156 </Table.Row>
157 </Table.Header>
158 <Table.Body>
159 <Table.Row>
160 <Table.Cell>
161 The first data model's `field` is of type string.
162 </Table.Cell>
163 <Table.Cell>
164 One-to-one relation
165 </Table.Cell>
166 </Table.Row>
167 <Table.Row>
168 <Table.Cell>
169 The first data model's `field` is of type array of strings.
170 </Table.Cell>
171 <Table.Cell>
172 One-to-many relation
173 </Table.Cell>
174 </Table.Row>
175 <Table.Row>
176 <Table.Cell>
177 The read-only module link is inversed.
178 </Table.Cell>
179 <Table.Cell>
180 One-to-many relation if multiple records in the second data model have the same ID of the first data model. Otherwise, one-to-one relation.
181 </Table.Cell>
182 </Table.Row>
183 </Table.Body>
184 </Table>
185
186 ### One-to-One Relation
187
188 Consider the first read-only module link you defined in this chapter:
189
190 ```ts
191 import BlogModule from "../modules/blog"
192 import ProductModule from "@medusajs/medusa/product"
193
194 export default defineLink(
195 {
196 linkable: BlogModule.linkable.post,
197 field: "product_id",
198 },
199 ProductModule.linkable.product,
200 {
201 readOnly: true,
202 }
203 )
204 ```
205
206 Since the `product_id` field of a post stores the ID of a single product, the link is a one-to-one relation. When querying a post, you'll get a single product object:
207
208 ```json title="Example Data"
209 [
210 {
211 "id": "post_123",
212 "product_id": "prod_123",
213 "product": {
214 "id": "prod_123",
215 // ...
216 }
217 }
218 ]
219 ```
220
221 ### One-to-Many Relation
222
223 Consider the read-only module link from the `post` data model uses an array of product IDs:
224
225 ```ts
226 import BlogModule from "../modules/blog"
227 import ProductModule from "@medusajs/medusa/product"
228
229 export default defineLink(
230 {
231 linkable: BlogModule.linkable.post,
232 field: "product_ids",
233 },
234 ProductModule.linkable.product,
235 {
236 readOnly: true,
237 }
238 )
239 ```
240
241 Where `product_ids` in the `post` data model is an array of strings. In this case, the link would be a one-to-many relation. So, an array of products would be returned when querying a post:
242
243 ```json title="Example Data"
244 [
245 {
246 "id": "post_123",
247 "product_ids": ["prod_123", "prod_124"],
248 "product": [
249 {
250 "id": "prod_123",
251 // ...
252 },
253 {
254 "id": "prod_124",
255 // ...
256 }
257 ]
258 }
259 ]
260 ```
261
262 ### Relation with Inversed Read-Only Link
263
264 If you define an inversed read-only module link where the ID of the linked record is stored in the second data model, the link can be either one-to-one or one-to-many based on the number of records in the second data model that have the same ID of the first data model.
265
266 For example, consider the `product` -> `post` link you defined in an earlier section:
267
268 ```ts
269 import BlogModule from "../modules/blog"
270 import ProductModule from "@medusajs/medusa/product"
271 import { defineLink } from "@medusajs/framework/utils"
272
273 export default defineLink(
274 {
275 linkable: ProductModule.linkable.product,
276 field: "id",
277 },
278 {
279 ...BlogModule.linkable.post.id,
280 primaryKey: "product_id",
281 },
282 {
283 readOnly: true,
284 }
285 )
286 ```
287
288 In the above snippet, the ID of the product is stored in the `post`'s `product_id` string field.
289
290 When you retrieve the post of a product, it may be a post object, or an array of post objects if multiple posts are linked to the product:
291
292 ```json title="Example Data"
293 [
294 {
295 "id": "prod_123",
296 "post": {
297 "id": "post_123",
298 "product_id": "prod_123"
299 // ...
300 }
301 },
302 {
303 "id": "prod_321",
304 "post": [
305 {
306 "id": "post_123",
307 "product_id": "prod_321"
308 // ...
309 },
310 {
311 "id": "post_124",
312 "product_id": "prod_321"
313 // ...
314 }
315 ]
316 }
317 ]
318 ```
319
320 If, however, you use an array field in `post`, the relation would always be one-to-many:
321
322 ```json title="Example Data"
323 [
324 {
325 "id": "prod_123",
326 "post": [
327 {
328 "id": "post_123",
329 "product_id": "prod_123"
330 // ...
331 }
332 ]
333 }
334 ]
335 ```
336
337 #### Force One-to-Many Relation
338
339 Alternatively, you can force a one-to-many relation by setting `isList` to `true` in the first data model's link configuration. For example:
340
341 ```ts
342 import BlogModule from "../modules/blog"
343 import ProductModule from "@medusajs/medusa/product"
344 import { defineLink } from "@medusajs/framework/utils"
345
346 export default defineLink(
347 {
348 linkable: ProductModule.linkable.product,
349 field: "id",
350 isList: true,
351 },
352 {
353 ...BlogModule.linkable.post.id,
354 primaryKey: "product_id",
355 },
356 {
357 readOnly: true,
358 }
359 )
360 ```
361
362 In this case, the relation would always be one-to-many, even if only one post is linked to a product:
363
364 ```json title="Example Data"
365 [
366 {
367 "id": "prod_123",
368 "post": [
369 {
370 "id": "post_123",
371 "product_id": "prod_123"
372 // ...
373 }
374 ]
375 }
376 ]
377 ```
378
379 ### Relation Name for Inverse Read-Only Links
380
381 Whether you're using a one-to-one or one-to-many relation for an inverse read-only module link, the relation name is always the alias of the second data model. It's not changed to its plural form for one-to-many relations.
382
383 For example, looking again at the forced one-to-many relation example:
384
385 ```ts
386 import BlogModule from "../modules/blog"
387 import ProductModule from "@medusajs/medusa/product"
388 import { defineLink } from "@medusajs/framework/utils"
389
390 export default defineLink(
391 {
392 linkable: ProductModule.linkable.product,
393 field: "id",
394 isList: true,
395 },
396 {
397 ...BlogModule.linkable.post.id,
398 primaryKey: "product_id",
399 },
400 {
401 readOnly: true,
402 }
403 )
404 ```
405
406 When querying a product, the relation name is still `post`, not `posts`:
407
408 export const relationNameHighlights = [
409 ["3", `"post.*"`, "The relation name is the alias of the second data model."],
410 ]
411
412 ```ts highlights={relationNameHighlights}
413 const { result } = await query.graph({
414 entity: "product",
415 fields: ["id", "post.*"],
416 filters: {
417 id: "prod_123",
418 },
419 })
420 ```
421
422 Consequently, the result will include a `post` property, even though it's an array of posts:
423
424 ```json title="Example Data"
425 [
426 {
427 "id": "prod_123",
428 "post": [
429 {
430 "id": "post_123",
431 "product_id": "prod_123"
432 // ...
433 }
434 ]
435 }
436 ]
437 ```
438
439 ---
440
441 ## Example: Read-Only Module Link for Virtual Data Models
442
443 Read-only module links are most useful when working with data models that aren't stored in your Medusa database. For example, data that is stored in a third-party system.
444
445 In those cases, you can define a read-only module link between a data model in Medusa and the data model in the external system, facilitating the retrieval of the linked data.
446
447 To define the read-only module link to a virtual data model, you must:
448
449 1. Define the read-only module link from the Medusa data model to the virtual data model.
450 2. Create a `list` method in the custom module's service. This method retrieves the linked records filtered by the ID(s) of the Medusa data model.
451 - You can also create a `listAndCount` method to retrieve the related records with pagination.
452 3. Use Query to retrieve the Medusa data model and its linked records from the virtual data model.
453
454 For example, consider you have a CMS Module that integrates a third-party Content-Management System (CMS) with Medusa, and you want to retrieve the posts in the CMS associated with a product in Medusa. The next steps showcase how to implement this.
455
456 ### a. Define Read-Only Module Link
457
458 Start by defining a read-only module link from the `Product` data model in Medusa to the external `post` data model in the CMS:
459
460 export const linkHighlights = [
461 ["8", "field", "The field to filter by."],
462 ["13", "alias", "The alias to use when querying the linked records."],
463 ["14", "primaryKey", "The primary key of the linked records. It's also used as the filter name."]
464 ]
465
466 ```ts title="src/links/product-cms.ts" highlights={linkHighlights}
467 import { defineLink } from "@medusajs/framework/utils"
468 import ProductModule from "@medusajs/medusa/product"
469 import { CMS_MODULE } from "../modules/cms"
470
471 export default defineLink(
472 {
473 linkable: ProductModule.linkable.product,
474 field: "id",
475 },
476 {
477 linkable: {
478 serviceName: CMS_MODULE,
479 alias: "cms_post",
480 primaryKey: "product_id",
481 },
482 },
483 {
484 readOnly: true,
485 }
486 )
487 ```
488
489 To define the read-only module link, you must pass to `defineLink`:
490
491 1. An object with the linkable configuration of the data model in Medusa, and the fields that will be passed as a filter to the CMS service.
492 - For example, if you want to filter by product title instead, you can pass `title` instead of `id`.
493 2. An object with the linkable configuration of the virtual data model in the CMS. This object must have the following properties:
494 - `serviceName`: The name of the service, which is the CMS Module's name. Medusa uses this name to resolve the module's service from the [Medusa container](../../medusa-container/page.mdx).
495 - `alias`: The alias to use when querying the linked records. You'll see how that works in a bit.
496 - `primaryKey`: The field in the CMS data model that holds the ID of a product.
497 3. The third parameter: an object with the `readOnly` property set to `true`.
498
499 ### b. Add List Methods to CMS Module Service
500
501 Next, add the following methods to the CMS Module's service:
502
503 export const serviceHighlights = [
504 ["4", "client", "An SDK to interact with the CMS API."],
505 ["9", "product_id", "The field to filter by. It must match the `primary_key` in the link configuration."],
506 ["32", "product_id", "The field to filter by. It must match the `primary_key` in the link configuration."]
507 ]
508
509 ```ts title="src/modules/cms/service.ts" highlights={serviceHighlights}
510 import { FindConfig } from "@medusajs/framework/types"
511
512 export default class CmsModuleService {
513 private client
514 // ...
515
516 async list(
517 filter: {
518 product_id: string | string[]
519 }
520 ) {
521 return this.client.getPosts(filter)
522 /**
523 * Example of returned data:
524 *
525 * [
526 * {
527 * "id": "post_123",
528 * "product_id": "prod_321"
529 * },
530 * {
531 * "id": "post_456",
532 * "product_id": "prod_654"
533 * }
534 * ]
535 */
536 }
537
538 // To retrieve with pagination
539 async listAndCount(
540 filter: {
541 product_id: string | string[]
542 },
543 config?: FindConfig<any> | undefined
544 ) {
545 return this.client.getPosts(filter, {
546 limit: config?.take,
547 offset: config?.skip,
548 })
549 /**
550 * Example of returned data:
551 *
552 * {
553 * count: 2,
554 * data: [
555 * {
556 * "id": "post_123",
557 * "product_id": "prod_321"
558 * },
559 * {
560 * "id": "post_456",
561 * "product_id": "prod_654"
562 * }
563 * ]
564 * }
565 */
566 }
567 }
568 ```
569
570 To retrieve the linked records, you must implement a `list` method in the CMS Module's service.
571
572 The `list` method accepts an object of filters holding the ID(s) of the products to retrieve their associated posts. The name of the filter property must match the `primary_key` defined in the link configuration, which is `product_id` in this case.
573
574 The returned posts must include the product's ID in a field with the same name as the `primary_key` option in the link configurations, which is `product_id` in this case.
575
576 You can also create a `listAndCount` method to retrieve the posts with pagination. This method is called if you pass [pagination parameters to Query](../../query/page.mdx#apply-pagination).
577
578 ### c. Query Linked Records
579
580 Now, you can use Query to retrieve a product and its linked post from the CMS:
581
582 export const queryHighlights = [
583 ["3", `"cms_post.*"`, "The `alias` of the virtual data model in the link configuration."]
584 ]
585
586 ```ts highlights={queryHighlights}
587 const { data } = await query.graph({
588 entity: "product",
589 fields: ["id", "cms_post.*"],
590 })
591 ```
592
593 In the above example, you pass `cms_post.*` in the fields, which is the `alias` of the virtual data model in the [link configuration](#a-define-read-only-module-link).
594
595 Each product will have a `cms_post` field that holds the posts whose `product_id` matches the product's ID. For example:
596
597 ```json title="Example Data"
598 [
599 {
600 "id": "prod_123",
601 "cms_post": {
602 "id": "post_123",
603 "product_id": "prod_123",
604 // ...
605 }
606 }
607 ]
608 ```
609
610 If multiple posts have their `product_id` set to a product's ID, an array of posts is returned instead:
611
612 ```json title="Example Data"
613 [
614 {
615 "id": "prod_123",
616 "cms_post": [
617 {
618 "id": "post_123",
619 "product_id": "prod_123",
620 // ...
621 },
622 {
623 "id": "post_124",
624 "product_id": "prod_123",
625 // ...
626 }
627 ]
628 }
629 ]
630 ```
631
632 <Note title="Recommended Tutorial">
633
634 [Sanity Integration Tutorial](!resources!/integrations/guides/sanity).
635
636 </Note>