5.4.2. Remote Link

In this chapter, you’ll learn what the remote link is and how to use it to manage links.

The remote link is a class with utility methods to manage links between data models. It’s registered in the Medusa container under the remoteLink registration name.

For example:

Code
8import { 9  RemoteLink,10} from "@medusajs/framework/modules-sdk"11
12export async function POST(13  req: MedusaRequest,14  res: MedusaResponse15): Promise<void> {16  const remoteLink: RemoteLink = req.scope.resolve(17    ContainerRegistrationKeys.REMOTE_LINK18  )19    20  // ...21}

You can use its methods to manage links, such as create or delete links.


To create a link between records of two data models, use the create method of the remote link.

For example:

Code
1import { Modules } from "@medusajs/framework/utils"2
3// ...4
5await remoteLink.create({6  [Modules.PRODUCT]: {7    product_id: "prod_123",8  },9  "helloModuleService": {10    my_custom_id: "mc_123",11  },12})

The create method accepts as a parameter an object. The object’s keys are the names of the linked modules.

ImportantThe keys (names of linked modules) must be in the same direction of the link definition.

The value of each module’s property is an object, whose keys are of the format {data_model_snake_name}_id, and values are the IDs of the linked record.

So, in the example above, you link a record of the MyCustom data model in a hello module to a Product record in the Product Module.


To remove a link between records of two data models, use the dismiss method of the remote link.

For example:

Code
1import { Modules } from "@medusajs/framework/utils"2
3// ...4
5await remoteLink.dismiss({6  [Modules.PRODUCT]: {7    product_id: "prod_123",8  },9  "helloModuleService": {10    my_custom_id: "mc_123",11  },12})

The dismiss method accepts the same parameter type as the create method.

ImportantThe keys (names of linked modules) must be in the same direction of the link definition.

Cascade Delete Linked Records#

If a record is deleted, use the delete method of the remote link to delete all linked records.

For example:

Code
1import { Modules } from "@medusajs/framework/utils"2
3// ...4
5await productModuleService.deleteVariants([variant.id])6
7await remoteLink.delete({8  [Modules.PRODUCT]: {9    product_id: "prod_123",10  },11})

This deletes all records linked to the deleted product.


Restore Linked Records#

If a record that was previously soft-deleted is now restored, use the restore method of the remote link to restore all linked records.

For example:

Code
1import { Modules } from "@medusajs/framework/utils"2
3// ...4
5await productModuleService.restoreProducts(["prod_123"])6
7await remoteLink.restore({8  [Modules.PRODUCT]: {9    product_id: "prod_123",10  },11})
Was this chapter helpful?
Edit this page