docs: add routing page (#9550)

- Add a new homepage to `book` project for the routing page
- Move all main doc pages to be under `/v2/learn` (and added redirects + fixed links across docs)
- Other: add admin components to resources dropdown + fixes to search on mobile.

Closes DX-955

Preview: https://docs-v2-git-docs-router-page-medusajs.vercel.app/v2
This commit is contained in:
Shahed Nasser
2024-10-18 08:24:34 +00:00
committed by GitHub
parent 7a47f5211d
commit 0a37675f0e
223 changed files with 2549 additions and 696 deletions
@@ -0,0 +1,58 @@
export const metadata = {
title: `${pageNumber} Admin Development Constraints`,
}
# {metadata.title}
This chapter lists some constraints of admin widgets and UI routes.
## Arrow Functions
Widget and UI route components must be created as arrow functions.
export const arrowHighlights = [
["2", "function", "Don't declare the widget / UI route as a function."],
["7", "() => ", "Use arrow functions when creating a widget / UI route."]
]
```ts highlights={arrowHighlights}
// Don't
function ProductWidget() {
// ...
}
// Do
const ProductWidget = () => {
// ...
}
```
---
## Widget Zone
A widget zone's value must be wrapped in double or single quotes. It can't be a template literal or a variable.
export const zoneHighlights = [
["3", "`product.details.before`", "Don't specify the value of `zone` as a template literal."],
["9", "ZONE", "Don't specify a variable as the value of `zone`."],
["14", `"product.details.before"`, "Wrap the value of `zone` in double or single quotes."]
]
```ts highlights={zoneHighlights}
// Don't
export const config = defineWidgetConfig({
zone: `product.details.before`,
})
// Don't
const ZONE = "product.details.after"
export const config = defineWidgetConfig({
zone: ZONE,
})
// Do
export const config = defineWidgetConfig({
zone: "product.details.before",
})
```
@@ -0,0 +1,26 @@
export const metadata = {
title: `${pageNumber} Admin Development`,
}
# {metadata.title}
In the next chapters, you'll learn more about possible admin customizations.
You can customize the admin dashboard by:
- Adding new sections to existing pages using Widgets.
- Adding new pages using UI Routes.
---
## Medusa UI Package
Medusa provides a Medusa UI package to facilitate your admin development through ready-made components and ensure a consistent design between your customizations and the dashboards design.
Refer to the [Medusa UI documentation](https://docs.medusajs.com/ui) to learn how to install it and use its components.
---
## Admin Components List
To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](!resources!/admin-component) to find common components.
@@ -0,0 +1,101 @@
export const metadata = {
title: `${pageNumber} Admin Development Tips`,
}
# {metadata.title}
In this chapter, you'll find some tips for your admin development.
## Send Requests to API Routes
To send a request to an API route in the Medusa Application, use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
For example:
export const fetchHighlights = [
["14", "fetch", "Send a request to the `/admin/products` API route."]
]
```tsx title="src/admin/widgets/product-widget.tsx" highlights={fetchHighlights}
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Container } from "@medusajs/ui"
import { useEffect, useState } from "react"
const ProductWidget = () => {
const [productsCount, setProductsCount] = useState(0)
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!loading) {
return
}
fetch(`/admin/products`, {
credentials: "include",
})
.then((res) => res.json())
.then(({ count }) => {
setProductsCount(count)
setLoading(false)
})
}, [loading])
return (
<Container className="divide-y p-0">
{loading && <span>Loading...</span>}
{!loading && <span>You have {productsCount} Product(s).</span>}
</Container>
)
}
export const config = defineWidgetConfig({
zone: "product.list.before",
})
export default ProductWidget
```
In this example, you send a request to the [List Products API route](!api!/admin#products_getproducts) and show the count of products in a widget.
---
## Routing Functionalities
To navigate or link to other pages, or perform other routing functionalities, use the [react-router-dom](https://reactrouter.com/en/main) package. It's installed in your project through the Medusa Admin.
For example:
export const highlights = [
["9", "Link", "Add a link to another page"],
["9", '"/orders', "Add the path without the `/app` prefix."]
]
```tsx title="src/admin/widgets/product-widget.tsx" highlights={highlights}
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Container } from "@medusajs/ui"
import { Link } from "react-router-dom"
// The widget
const ProductWidget = () => {
return (
<Container className="divide-y p-0">
<Link to={"/orders"}>View Orders</Link>
</Container>
)
}
// The widget's configurations
export const config = defineWidgetConfig({
zone: "product.details.before",
})
export default ProductWidget
```
This adds a widget in a product's details page with a link to the Orders page. The link's path must be without the `/app` prefix.
<Note title="Learn more">
Refer to [react-router-doms documentation](https://reactrouter.com/en/main) for other available components and hooks.
</Note>
@@ -0,0 +1,168 @@
export const metadata = {
title: `${pageNumber} Admin UI Routes`,
}
# {metadata.title}
In this chapter, youll learn how to create a UI route in the admin dashboard.
## What is a UI Route?
A UI route is a React Component that adds a new page to your admin dashboard. The UI Route can be shown in the sidebar or added as a nested page.
For example, you may add a new page to manage product reviews.
---
## How to Create a UI Route?
A UI route is created in a file named `page.tsx` under the `src/admin/routes` directory. The files default export must be the UI routes React component.
For example, create the file `src/admin/routes/custom/page.tsx` with the following content:
```tsx title="src/admin/routes/custom/page.tsx"
import { Container, Heading } from "@medusajs/ui"
const CustomPage = () => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h2">This is my custom route</Heading>
</div>
</Container>
)
}
export default CustomPage
```
The new pages path is the files path relative to `src/admin/routes`. So, the above UI route is a new page added at the path `localhost:9000/app/custom`.
<Note title="Important" type="warning">
The UI route component must be created as an arrow function.
</Note>
---
## Test the UI Route
To test the UI route, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, after logging into the admin dashboard, open the page `localhost:9000/app/custom` to see your custom page.
---
## Show UI Route in the Sidebar
A UI route file can export a configuration object that indicates a new item must be added in the sidebar linking to the new UI route.
For example:
export const highlights = [
["16", "label", "The label of the UI route's sidebar item."],
["17", "icon", "The icon of the UI route's sidebar item."]
]
```tsx title="src/admin/routes/custom/page.tsx" highlights={highlights}
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { ChatBubbleLeftRight } from "@medusajs/icons"
import { Container, Heading } from "@medusajs/ui"
const CustomPage = () => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h2">This is my custom route</Heading>
</div>
</Container>
)
}
export const config = defineRouteConfig({
label: "Custom Route",
icon: ChatBubbleLeftRight,
})
export default CustomPage
```
The configuration object is created using the `defineRouteConfig` function imported from `@medusajs/admin-sdk`. It accepts the following properties:
- `label`: the sidebar items label.
- `icon`: an optional React component used as an icon in the sidebar.
The above example adds a new sidebar item with the label `Custom Route` and an icon from the [Medusa UI Icons package](!ui!/icons/overview).
---
## Create Settings Page
To create a page under the settings section of the admin dashboard, create the UI route file under the path `src/admin/routes/settings`.
For example:
```tsx title="src/admin/routes/settings/custom/page.tsx"
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { Container, Heading } from "@medusajs/ui"
const CustomSettingPage = () => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h1">Custom Setting Page</Heading>
</div>
</Container>
)
}
export const config = defineRouteConfig({
label: "Custom",
})
export default CustomSettingPage
```
This adds a page under the path `/app/settings/custom`. An item is also added to the settings sidebar with the label `Custom`.
---
## Path Parameters
A UI route can accept path parameters if the name of any of the directories in its path is of the format `[param]`.
For example, create the file `src/admin/routes/custom/[id]/page.tsx` with the following content:
```tsx title="src/admin/routes/custom/[id]/page.tsx" highlights={[["5", "", "Retrieve the path parameter."], ["10", "{id}", "Show the path parameter."]]}
import { useParams } from "react-router-dom"
import { Container } from "@medusajs/ui"
const CustomPage = () => {
const { id } = useParams()
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h1">Passed ID: {id}</Heading>
</div>
</Container>
)
}
export default CustomPage
```
You access the passed parameter using `react-router-dom`'s [useParams hook](https://reactrouter.com/en/main/hooks/use-params).
If you run the Medusa application and go to `localhost:9000/app/custom/123`, you'll see `123` printed in the page.
---
## Admin Components List
To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](!resources!/admin-component) to find common components.
@@ -0,0 +1,130 @@
import { Table } from "docs-ui"
export const metadata = {
title: `${pageNumber} Admin Widgets`,
}
# {metadata.title}
In this chapter, youll learn more about widgets and how to use them.
## What is an Admin Widget?
Admin widgets are React components you inject into predetermined injection zones in the Medusa Admin dashboard.
For example, you can add a widget on the order details page that shows payment details retrieved from Stripe.
---
## How to Create a Widget?
A widget is created in a file under the `src/admin/widgets` directory. The files default export must be the widget, which is the React component. The file must also export the widgets configurations.
For example, create the file `src/admin/widgets/product-widget.tsx` with the following content:
export const widgetHighlights = [
["5", "ProductWidget", "The React component of the product widget."],
["17", "zone", "The zone to inject the widget to."]
]
```tsx title="src/admin/widgets/product-widget.tsx" highlights={widgetHighlights}
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Container, Heading } from "@medusajs/ui"
// The widget
const ProductWidget = () => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h2">Product Widget</Heading>
</div>
</Container>
)
}
// The widget's configurations
export const config = defineWidgetConfig({
zone: "product.details.before",
})
export default ProductWidget
```
The widget only shows the heading `Product Widget`.
Use the `defineWidgetConfig` function imported from `@medusajs/admin-sdk` to create and export the widget's configurations. It accepts as a parameter an object with the following property:
- `zone`: A string or an array of strings, each being the name of the zone to inject the widget into.
In the example above, the widget is injected at the top of a products details.
<Note title="Important" type="warning">
The widget component must be created as an arrow function.
</Note>
---
## Test the Widget
To test out the widget, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, open a products details page. Youll find your custom widget at the top of the page.
---
## Detail Widget Props
Widgets that are injected into a details page (for example, `product.details.before`) receive a `data` prop, which is the main data of the details page (for example, the product object).
For example:
export const detailHighlights = [
["10", "data", "Receive the data as a prop."],
["11", "AdminProduct", "Pass the expected type of `data` as a type argument."],
["16", "data.title", "Show the product's title."]
]
```tsx title="src/admin/widgets/product-widget.tsx" highlights={detailHighlights}
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Container, Heading } from "@medusajs/ui"
import {
DetailWidgetProps,
AdminProduct,
} from "@medusajs/framework/types"
// The widget
const ProductWidget = ({
data,
}: DetailWidgetProps<AdminProduct>) => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h2">
Product Widget {data.title}
</Heading>
</div>
</Container>
)
}
// The widget's configurations
export const config = defineWidgetConfig({
zone: "product.details.before",
})
export default ProductWidget
```
Notice that the type of the props is `DetailWidgetProps`, which accepts as a type argument the expected type of `data`.
---
## Injection Zone
Refer to [this reference](!resources!/admin-widget-injection-zones) for the full list of injection zones and their props.
@@ -0,0 +1,207 @@
import { Details } from "docs-ui"
export const metadata = {
title: `${pageNumber} Pass Additional Data to Medusa's API Route`,
}
# {metadata.title}
In this chapter, you'll learn how to pass additional data in requests to Medusa's API Route.
## Why Pass Additional Data?
Some of Medusa's API Routes accept an `additional_data` parameter whose type is an object. The API Route passes the `additional_data` to the workflow, which in turn passes it to its hooks.
This is useful when you have a link from your custom module to a commerce module, and you want to perform an additional action when a request is sent to an existing API route.
For example, the [Create Product API Route](!api!/admin#products_postproducts) accepts an `additional_data` parameter. If you have a data model linked to it, you consume the `productsCreated` hook to create a record of the data model using the custom data and link it to the product.
### API Routes Accepting Additional Data
<Details summaryContent="API Routes List">
- Campaigns
- [Create Campaign](!api!/admin#campaigns_postcampaigns)
- [Update Campaign](!api!/admin#campaigns_postcampaignsid)
- Cart
- [Create Cart](!api!/store#carts_postcarts)
- [Update Cart](!api!/store#carts_postcartsid)
- Customers
- [Create Customer](!api!/admin#customers_postcustomers)
- [Update Customer](!api!/admin#customers_postcustomersid)
- [Create Address](!api!/admin#customers_postcustomersidaddresses)
- [Update Address](!api!/admin#customers_postcustomersidaddressesaddress_id)
- Draft Orders
- [Create Draft Order](!api!/admin#draft-orders_postdraftorders)
- Orders
- [Complete Orders](!api!/admin#orders_postordersidcomplete)
- [Cancel Order's Fulfillment](!api!/admin#orders_postordersidfulfillmentsfulfillment_idcancel)
- [Create Shipment](!api!/admin#orders_postordersidfulfillmentsfulfillment_idshipments)
- [Create Fulfillment](!api!/admin#orders_postordersidfulfillments)
- Products
- [Create Product](!api!/admin#products_postproducts)
- [Update Product](!api!/admin#products_postproductsid)
- [Create Product Variant](!api!/admin#products_postproductsidvariants)
- [Update Product Variant](!api!/admin#products_postproductsidvariantsvariant_id)
- [Create Product Option](!api!/admin#products_postproductsidoptions)
- [Update Product Option](!api!/admin#products_postproductsidoptionsoption_id)
- Promotions
- [Create Promotion](!api!/admin#promotions_postpromotions)
- [Update Promotion](!api!/admin#promotions_postpromotionsid)
</Details>
---
## How to Pass Additional Data
### 1. Specify Validation of Additional Data
Before passing custom data in the `additional_data` object parameter, you must specify validation rules for the allowed properties in the object.
To do that, use the middleware route object defined in `src/api/middlewares.ts`.
For example, create the file `src/api/middlewares.ts` with the following content:
```ts title="src/api/middlewares.ts"
import { defineMiddlewares } from "@medusajs/medusa"
import { z } from "zod"
export default defineMiddlewares({
routes: [
{
method: "POST",
matcher: "/admin/products",
additionalDataValidator: {
brand: z.string().optional(),
},
},
],
})
```
The middleware route object accepts an optional parameter `additionalDataValidator` whose value is an object of key-value pairs. The keys indicate the name of accepted properties in the `additional_data` parameter, and the value is [Zod](https://zod.dev/) validation rules of the property.
In this example, you indicate that the `additional_data` parameter accepts a `brand` property whose value is an optional string.
<Note>
Refer to [Zod's documentation](https://zod.dev) for all available validation rules.
</Note>
### 2. Pass the Additional Data in a Request
You can now pass a `brand` property in the `additional_data` parameter of a request to the Create Product API Route.
For example:
```bash
curl -X POST 'http://localhost:9000/admin/products' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer {token}' \
--data '{
"title": "Product 1",
"options": [
{
"title": "Default option",
"values": ["Default option value"]
}
],
"additional_data": {
"brand": "Acme"
}
}'
```
<Note title="Tip">
Make sure to replace the `{token}` in the authorization header with an admin user's authentication token.
</Note>
In this request, you pass in the `additional_data` parameter a `brand` property and set its value to `Acme`.
The `additional_data` is then passed to hooks in the `createProductsWorkflow` used by the API route.
---
## Use Additional Data in a Hook
<Note>
Learn about workflow hooks in [this guide](../../workflows/workflow-hooks/page.mdx).
</Note>
Step functions consuming the workflow hook can access the `additional_data` in the first parameter.
For example, consider you want to store the data passed in `additional_data` in the product's `metadata` property.
To do that, create the file `src/workflows/hooks/product-created.ts` with the following content:
```ts title="src/workflows/hooks/product-created.ts"
import { StepResponse } from "@medusajs/framework/workflows-sdk"
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
import { Modules } from "@medusajs/framework/utils"
createProductsWorkflow.hooks.productsCreated(
async ({ products, additional_data }, { container }) => {
if (!additional_data.brand) {
return
}
const productModuleService = container.resolve(
Modules.PRODUCT
)
await productModuleService.upsertProducts(
products.map((product) => ({
...product,
metadata: {
...product.metadata,
brand: additional_data.brand,
},
}))
)
return new StepResponse(products, {
products,
additional_data,
})
}
)
```
This consumes the `productsCreated` hook, which runs after the products are created.
If `brand` is passed in `additional_data`, you resolve the Product Module's main service and use its `upsertProducts` method to update the products, adding the brand to the `metadata` property.
### Compensation Function
Hooks also accept a compensation function as a second parameter to undo the actions made by the step function.
For example, pass the following second parameter to the `productsCreated` hook:
```ts title="src/workflows/hooks/product-created.ts"
createProductsWorkflow.hooks.productsCreated(
async ({ products, additional_data }, { container }) => {
// ...
},
async ({ products, additional_data }, { container }) => {
if (!additional_data.brand) {
return
}
const productModuleService = container.resolve(
Modules.PRODUCT
)
await productModuleService.upsertProducts(
products
)
}
)
```
This updates the product to their original state before adding the brand to their `metadata` property.
@@ -0,0 +1,120 @@
export const metadata = {
title: `${pageNumber} Handling CORS in API Routes`,
}
# {metadata.title}
In this chapter, youll learn about the CORS middleware and how to configure it for custom API routes.
## CORS Overview
Cross-Origin Resource Sharing (CORS) allows only configured origins to access your API Routes.
For example, if you allow only origins starting with `http://localhost:7001` to access your Admin API Routes, other origins accessing those routes get a CORS error.
### CORS Configurations
The `storeCors` and `adminCors` properties of Medusa's `http` configuration set the allowed origins for routes starting with `/store` and `/admin` respectively.
These configurations accept a URL pattern to identify allowed origins.
For example:
```js title="medusa-config.ts"
module.exports = defineConfig({
projectConfig: {
http: {
storeCors: "http://localhost:8000",
adminCors: "http://localhost:7001",
// ...
},
},
})
```
This allows the `http://localhost:7001` origin to access the Admin API Routes, and the `http://localhost:8000` origin to access Store API Routes.
<Note title="Tip">
Learn more about the CORS configurations in [this resource guide](!resources!/references/medusa-config#http).
</Note>
---
## CORS in Store and Admin Routes
To disable the CORS middleware for a route, export a `CORS` variable in the route file with its value set to `false`.
For example:
```ts title="src/api/store/custom/route.ts" highlights={[["15"]]}
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "[GET] Hello world!",
})
}
export const CORS = false
```
This disables the CORS middleware on API Routes at the path `/store/custom`.
---
## CORS in Custom Routes
If you create a route that doesnt start with `/store` or `/admin`, you must apply the CORS middleware manually. Otherwise, all requests to your API route lead to a CORS error.
You can do that in the exported middlewares configurations in `src/api/middlewares.ts`.
For example:
export const highlights = [["25", "parseCorsOrigins", "A utility function that parses the CORS configurations in `medusa-config.ts`"]]
```ts title="src/api/middlewares.ts" highlights={highlights} collapsibleLines="1-10" expandButtonLabel="Show Imports"
import { defineMiddlewares } from "@medusajs/medusa"
import type {
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { ConfigModule } from "@medusajs/framework/types"
import { parseCorsOrigins } from "@medusajs/framework/utils"
import cors from "cors"
export default defineMiddlewares({
routes: [
{
matcher: "/custom*",
middlewares: [
(
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) => {
const configModule: ConfigModule =
req.scope.resolve("configModule")
return cors({
origin: parseCorsOrigins(
configModule.projectConfig.http.storeCors
),
credentials: true,
})(req, res, next)
},
],
},
],
})
```
This retrieves the configurations exported from `medusa-config.ts` and applies the `storeCors` to routes starting with `/custom`.
@@ -0,0 +1,284 @@
import { Table } from "docs-ui"
export const metadata = {
title: `${pageNumber} Throwing and Handling Errors`,
}
# {metadata.title}
In this guide, you'll learn how to throw errors in your Medusa application, how it affects an API route's response, and how to change the default error handler of your Medusa application.
## Throw MedusaError
When throwing an error in your API routes, middlewares, workflows, or any customization, throw a `MedusaError`, which is imported from `@medusajs/framework/utils`.
The Medusa application's API route error handler then wraps your thrown error in a uniform object and returns it in the response.
For example:
```ts
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { MedusaError } from "@medusajs/framework/utils"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
if (!req.query.q) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"The `q` query parameter is required."
)
}
// ...
}
```
The `MedusaError` class accepts in its constructor two parameters:
1. The first is the error's type. `MedusaError` has a static property `Types` that you can use. `Types` is an enum whose possible values are explained in the next section.
2. The second is the message to show in the error response.
### Error Object in Response
The error object returned in the response has two properties:
- `type`: The error's type.
- `message`: The error message, if available.
- `code`: A common snake-case code. Its values can be:
- `invalid_request_error` for the `DUPLICATE_ERROR` type.
- `api_error`: for the `DB_ERROR` type.
- `invalid_state_error` for `CONFLICT` error type.
- `unknown_error` for any unidentified error type.
- For other error types, this property won't be available unless you provide a code as a third parameter to the `MedusaError` constructor.
### MedusaError Types
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Type</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell className="w-1/5">Status Code</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`DB_ERROR`
</Table.Cell>
<Table.Cell>
Indicates a database error.
</Table.Cell>
<Table.Cell>
`500`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`DUPLICATE_ERROR`
</Table.Cell>
<Table.Cell>
Indicates a duplicate of a record already exists. For example, when trying to create a customer whose email is registered by another customer.
</Table.Cell>
<Table.Cell>
`422`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`INVALID_ARGUMENT` and `UNEXPECTED_STATE`
</Table.Cell>
<Table.Cell>
Indicates an error that occurred due to incorrect arguments or other unexpected state.
</Table.Cell>
<Table.Cell>
`500`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`INVALID_DATA`
</Table.Cell>
<Table.Cell>
Indicates a validation error.
</Table.Cell>
<Table.Cell>
`400`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`UNAUTHORIZED`
</Table.Cell>
<Table.Cell>
Indicates that a user is not authorized to perform an action or access a route.
</Table.Cell>
<Table.Cell>
`401`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`NOT_FOUND`
</Table.Cell>
<Table.Cell>
Indicates that the requested resource, such as a route or a record, isn't found.
</Table.Cell>
<Table.Cell>
`404`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`NOT_ALLOWED`
</Table.Cell>
<Table.Cell>
Indicates that an operation isn't allowed.
</Table.Cell>
<Table.Cell>
`400`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`CONFLICT`
</Table.Cell>
<Table.Cell>
Indicates that a request conflicts with another previous or ongoing request. The error message in this case is ignored for a default message.
</Table.Cell>
<Table.Cell>
`409`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`PAYMENT_AUTHORIZATION_ERROR`
</Table.Cell>
<Table.Cell>
Indicates an error has occurred while authorizing a payment.
</Table.Cell>
<Table.Cell>
`422`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
Other error types
</Table.Cell>
<Table.Cell>
Any other error type results in an `unknown_error` code and message.
</Table.Cell>
<Table.Cell>
`500`
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
---
## Override Error Handler
The `defineMiddlewares` function used to apply middlewares on routes accepts an `errorHandler` in its object parameter. Use it to override the default error handler for API routes.
<Note>
This error handler will also be used for errors thrown in Medusa's API routes and resources.
</Note>
For example, create `src/api/middlewares.ts` with the following:
```ts title="src/api/middlewares.ts" collapsibleLines="1-8" expandMoreLabel="Show Imports"
import {
defineMiddlewares,
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { MedusaError } from "@medusajs/framework/utils"
export default defineMiddlewares({
errorHandler: (
error: MedusaError | any,
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) => {
res.status(400).json({
error: "Something happened.",
})
},
})
```
The `errorHandler` property's value is a function that accepts four parameters:
1. The error thrown. Its type can be `MedusaError` or any other thrown error type.
2. A request object of type `MedusaRequest`.
3. A response object of type `MedusaResponse`.
4. A function of type MedusaNextFunction that executes the next middleware in the stack.
This example overrides Medusa's default error handler with a handler that always returns a `400` status code with the same message.
@@ -0,0 +1,45 @@
export const metadata = {
title: `${pageNumber} HTTP Methods`,
}
# {metadata.title}
In this chapter, you'll learn about how to add new API routes for each HTTP method.
## HTTP Method Handler
An API route is created for every HTTP method you export a handler function for in a route file.
Allowed HTTP methods are: `GET`, `POST`, `DELETE`, `PUT`, `PATCH`, `OPTIONS`, and `HEAD`.
For example, create the file `src/api/hello-world/route.ts` with the following content:
```ts title="src/api/hello-world/route.ts"
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "[GET] Hello world!",
})
}
export const POST = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "[POST] Hello world!",
})
}
```
This adds two API Routes:
- A `GET` route at `http://localhost:9000/hello-world`.
- A `POST` route at `http://localhost:9000/hello-world`.
@@ -0,0 +1,217 @@
export const metadata = {
title: `${pageNumber} Middlewares`,
}
# {metadata.title}
In this chapter, youll learn about middlewares and how to create them.
## What is a Middleware?
A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler function.
Middlwares are used to guard API routes, parse request content types other than `application/json`, manipulate request data, and more.
<Note title="Tip">
As Medusa's server is based on Express, you can use any [Express middleware](https://expressjs.com/en/resources/middleware.html).
</Note>
---
## How to Create a Middleware?
Middlewares are defined in the special file `src/api/middlewares.ts`. Use the `defineMiddlewares` function imported from `@medusajs/medusa` to define the middlewares, and export its value.
For example:
```ts title="src/api/middlewares.ts"
import { defineMiddlewares } from "@medusajs/medusa"
import type {
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export default defineMiddlewares({
routes: [
{
matcher: "/custom*",
middlewares: [
(
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) => {
console.log("Received a request!")
next()
},
],
},
],
})
```
The `defineMiddlewares` function accepts a middleware configurations object that has the property `routes`. `routes`'s value is an array of middleware route objects, each having the following properties:
- `matcher`: a string or regular expression indicating the API route path to apply the middleware on. The regular expression must be compatible with [path-to-regexp](https://github.com/pillarjs/path-to-regexp).
- `middlewares`: An array of middleware functions.
In the example above, you define a middleware that logs the message `Received a request!` whenever a request is sent to an API route path starting with `/custom`.
---
## Test the Middleware
To test the middleware:
1. Start the application:
```bash npm2yarn
npm run dev
```
2. Send a request to any API route starting with `/custom`.
3. See the following message in the terminal:
```bash
Received a request!
```
---
## When to Use Middlewares
<Note type="success" title="Use middlewares when">
- You want to protect API routes by a custom condition.
- You're modifying the request body.
</Note>
---
## Middleware Function Parameters
The middleware function accepts three parameters:
1. A request object of type `MedusaRequest`.
2. A response object of type `MedusaResponse`.
3. A function of type `MedusaNextFunction` that executes the next middleware in the stack.
<Note title="Important">
You must call the `next` function in the middleware. Otherwise, other middlewares and the API route handler wont execute.
</Note>
---
## Middleware for Routes with Path Parameters
To indicate a path parameter in a middleware's `matcher` pattern, use the format `:{param-name}`.
For example:
export const pathParamHighlights = [["11", ":id", "Indicates that the API route accepts an `id` path parameter."]]
```ts title="src/api/middlewares.ts" collapsibleLines="1-7" expandMoreLabel="Show Imports" highlights={pathParamHighlights}
import { defineMiddlewares } from "@medusajs/medusa"
import type {
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export default defineMiddlewares({
routes: [
{
matcher: "/custom/:id",
middlewares: [
// ...
],
},
],
})
```
This applies a middleware to the routes defined in the file `src/api/custom/[id]/route.ts`.
---
## Restrict HTTP Methods
Restrict which HTTP methods the middleware is applied to using the `method` property of the middleware route object.
For example:
export const highlights = [["12", "method", "Apply the middleware only on `POST` requests"]]
```ts title="src/api/middlewares.ts" highlights={highlights} collapsibleLines="1-7" expandButtonLabel="Show Imports"
import { defineMiddlewares } from "@medusajs/medusa"
import type {
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export default defineMiddlewares({
routes: [
{
matcher: "/custom*",
method: ["POST", "PUT"],
middlewares: [
// ...
],
},
],
})
```
`method`'s value is one or more HTTP methods to apply the middleware to.
This example applies the middleware only when a `POST` or `PUT` request is sent to an API route path starting with `/custom`.
---
## Request URLs with Trailing Backslashes
A middleware whose `matcher` pattern doesn't end with a backslash won't be applied for requests to URLs with a trailing backslash.
For example, consider you have the following middleware:
```ts collapsibleLines="1-7" expandMoreLabel="Show Imports"
import { defineMiddlewares } from "@medusajs/medusa"
import type {
MedusaNextFunction,
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export default defineMiddlewares({
routes: [
{
matcher: "/custom",
middlewares: [
(
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) => {
console.log("Received a request!")
next()
},
],
},
],
})
```
If you send a request to `http://localhost:9000/custom`, the middleware will run.
However, if you send a request to `http://localhost:9000/custom/`, the middleware won't run.
In general, avoid adding trailing backslashes when sending requests to API routes.
@@ -0,0 +1,14 @@
export const metadata = {
title: `${pageNumber} API Routes Advanced Guides`,
}
# {metadata.title}
In the next chapters, you'll focus more on API routes to learn about topics such as:
- Creating API routes for different HTTP methods.
- Accepting parameters in your API routes.
- Formatting response data and headers.
- Applying middlewares on API routes.
- Validating request body parameters.
- Protecting API routes by requiring user authentication.
@@ -0,0 +1,155 @@
export const metadata = {
title: `${pageNumber} API Route Parameters`,
}
# {metadata.title}
In this chapter, youll learn about path, query, and request body parameters.
## Path Parameters
To create an API route that accepts a path parameter, create a directory within the route file's path whose name is of the format `[param]`.
For example, to create an API Route at the path `/hello-world/:id`, where `:id` is a path parameter, create the file `src/api/hello-world/[id]/route.ts` with the following content:
export const singlePathHighlights = [
["11", "req.params.id", "Access the path parameter `id`"]
]
```ts title="src/api/hello-world/[id]/route.ts" highlights={singlePathHighlights}
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: `[GET] Hello ${req.params.id}!`,
})
}
```
The `MedusaRequest` object has a `params` property. `params` holds the path parameters in key-value pairs.
### Multiple Path Parameters
To create an API route that accepts multiple path parameters, create within the file's path multiple directories whose names are of the format `[param]`.
For example, to create an API route at `/hello-world/:id/name/:name`, create the file `src/api/hello-world/[id]/name/[name]/route.ts` with the following content:
export const multiplePathHighlights = [
["12", "req.params.id", "Access the path parameter `id`"],
["13", "req.params.name", "Access the path parameter `name`"]
]
```ts title="src/api/hello-world/[id]/name/[name]/route.ts" highlights={multiplePathHighlights}
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: `[GET] Hello ${
req.params.id
} - ${req.params.name}!`,
})
}
```
You access the `id` and `name` path parameters using the `req.params` property.
---
## Query Parameters
You can access all query parameters in the `query` property of the `MedusaRequest` object. `query` is an object of key-value pairs, where the key is a query parameter's name, and the value is its value.
For example:
export const queryHighlights = [
["11", "req.query.name", "Access the query parameter `name`"],
]
```ts title="src/api/hello-world/route.ts" highlights={queryHighlights}
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: `Hello ${req.query.name}`,
})
}
```
The value of `req.query.name` is the value passed in `?name=John`, for example.
---
## Request Body Parameters
The Medusa application parses the body of any request having its `Content-Type` header set to `application/json`. The request body parameters are set in the `MedusaRequest`'s `body` property.
For example:
export const bodyHighlights = [
["11", "HelloWorldReq", "Specify the type of the request body parameters."],
["15", "req.body.name", "Access the request body parameter `name`"],
]
```ts title="src/api/hello-world/route.ts" highlights={bodyHighlights}
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
type HelloWorldReq = {
name: string
}
export const POST = async (
req: MedusaRequest<HelloWorldReq>,
res: MedusaResponse
) => {
res.json({
message: `[POST] Hello ${req.body.name}!`,
})
}
```
In this example, you use the `name` request body parameter to create the message in the returned response.
<Note title="Tip">
The `MedusaRequest` type accepts a type argument that indicates the type of the request body. This is useful for auto-completion and to avoid typing errors.
</Note>
To test it out, send the following request to your Medusa application:
```bash
curl -X POST 'http://localhost:9000/hello-world' \
-H 'Content-Type: application/json' \
--data-raw '{
"name": "John"
}'
```
This returns the following JSON object:
```json
{
"message": "[POST] Hello John!"
}
```
@@ -0,0 +1,182 @@
export const metadata = {
title: `${pageNumber} Protected Routes`,
}
# {metadata.title}
In this chapter, youll learn how to create protected routes.
## What is a Protected Route?
A protected route is a route that requires requests to be user-authenticated before performing the route's functionality. Otherwise, the request fails, and the user is prevented access.
---
## Default Protected Routes
Medusa applies an authentication guard on routes starting with `/admin`, including custom API routes.
Requests to `/admin` must be user-authenticated to access the route.
<Note title="Tip">
Refer to the API Reference for [Admin](!api!/admin#authentication) and [Store](!api!/store#authentication) authentication methods.
</Note>
---
## Protect Custom API Routes
To protect custom API Routes to only allow authenticated customer or admin users, use the `authenticate` middleware imported from `@medusajs/medusa`.
For example:
export const highlights = [
[
"10",
"authenticate",
"Only authenticated admin users can access routes starting with `/custom/admin`",
],
[
"14",
"authenticate",
"Only authenticated customers can access routes starting with `/custom/customers`",
],
]
```ts title="src/api/middlewares.ts" highlights={highlights}
import {
defineMiddlewares,
authenticate,
} from "@medusajs/medusa"
export default defineMiddlewares({
routes: [
{
matcher: "/custom/admin*",
middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
},
{
matcher: "/custom/customer*",
middlewares: [authenticate("customer", ["session", "bearer"])],
},
],
})
```
The `authenticate` middleware function accepts three parameters:
1. The type of user authenticating. Use `user` for authenticating admin users, and `customer` for authenticating customers. You can also pass `*` to allow all types of users.
2. An array of the types of authentication methods allowed. Both `user` and `customer` scopes support `session` and `bearer`. The `admin` scope also supports the `api-key` authentication method.
3. An optional object of configurations accepting the following property:
- `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too.
---
## Authentication Opt-Out
To disable the authentication guard on custom routes under the `/admin` path prefix, export an `AUTHENTICATE` variable in the route file with its value set to `false`.
For example:
```ts title="src/api/admin/custom/route.ts" highlights={[["15"]]}
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "Hello",
})
}
export const AUTHENTICATE = false
```
Now, any request sent to the `/admin/custom` API route is allowed, regardless if the admin user is authenticated.
---
## Authenticated Request Type
To access the authentication details in an API route, such as the logged-in user's ID, set the type of the first request parameter to `AuthenticatedMedusaRequest`. It extends `MedusaRequest`.
The `auth_context.actor_id` property of `AuthenticatedMedusaRequest` holds the ID of the authenticated user or customer. If there isn't any authenticated user or customer, `auth_context` is `undefined`.
<Note>
If you opt-out of authentication in a route as mentioned in the [previous section](#authentication-opt-out), you can't access the authenticated user or customer anymore. Use the [authenticate middleware](#protect-custom-api-routes) instead.
</Note>
### Retrieve Logged-In Customer's Details
You can access the logged-in customers ID in all API routes starting with `/store` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object.
For example:
```ts title="src/api/store/custom/route.ts" highlights={[["19", "req.auth_context.actor_id", "Access the logged-in customer's ID."]]} collapsibleLines="1-7" expandButtonLabel="Show Imports"
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"
import { ICustomerModuleService } from "@medusajs/framework/types"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
if (req.auth_context?.actor_id) {
// retrieve customer
const customerModuleService: ICustomerModuleService = req.scope.resolve(
Modules.CUSTOMER
)
const customer = await customerModuleService.retrieveCustomer(
req.auth_context.actor_id
)
}
// ...
}
```
In this example, you resolve the Customer Module's main service, then use it to retrieve the logged-in customer, if available.
### Retrieve Logged-In Admin User's Details
You can access the logged-in admin users ID in all API Routes starting with `/admin` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object.
For example:
```ts title="src/api/admin/custom/route.ts" highlights={[["17", "req.auth_context.actor_id", "Access the logged-in admin user's ID."]]} collapsibleLines="1-7" expandButtonLabel="Show Imports"
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"
import { IUserModuleService } from "@medusajs/framework/types"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const userModuleService: IUserModuleService = req.scope.resolve(
Modules.USER
)
const user = await userModuleService.retrieveUser(
req.auth_context.actor_id
)
// ...
}
```
In the route handler, you resolve the User Module's main service, then use it to retrieve the logged-in admin user.
@@ -0,0 +1,121 @@
export const metadata = {
title: `${pageNumber} API Route Response`,
}
# {metadata.title}
In this chapter, you'll learn how to send a response in your API route.
## Send a JSON Response
To send a JSON response, use the `json` method of the `MedusaResponse` object passed as the second parameter of your API route handler.
For example:
export const jsonHighlights = [
["7", "json", "Return a JSON object."]
]
```ts title="src/api/custom/route.ts" highlights={jsonHighlights}
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "Hello, World!",
})
}
```
This API route returns the following JSON object:
```json
{
"message": "Hello, World!"
}
```
---
## Set Response Status Code
By default, setting the JSON data using the `json` method returns a response with a `200` status code.
To change the status code, use the `status` method of the `MedusaResponse` object.
For example:
export const statusHighlight = [
["7", "status", "Set the response code to `201`."]
]
```ts title="src/api/custom/route.ts" highlights={statusHighlight}
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.status(201).json({
message: "Hello, World!",
})
}
```
The response of this API route has the status code `201`.
---
## Change Response Content Type
To return response data other than a JSON object, use the `writeHead` method of the `MedusaResponse` object. It allows you to set the response headers, including the content type.
For example, to create an API route that returns an event stream:
export const streamHighlights = [
["7", "writeHead", "Set the response's headers."],
["7", "200", "Set the status code."],
["8", `"Content-Type"`, "Set the response's content type."],
["13", "interval", "Simulate stream data using an interval"],
["14", "write", "Write stream data."],
["17", "on", "Stop the stream when the request is terminated."]
]
```ts highlights={streamHighlights}
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
})
const interval = setInterval(() => {
res.write("Streaming data...\n")
}, 3000)
req.on("end", () => {
clearInterval(interval)
res.end()
})
}
```
The `writeHead` method accepts two parameters:
1. The first one is the response's status code.
2. The second is an object of key-value pairs to set the headers of the response.
This API route opens a stream by setting the `Content-Type` in the header to `text/event-stream`. It then simulates a stream by creating an interval that writes the stream data every three seconds.
---
## Do More with Responses
The `MedusaResponse` type is based on [Express's Response](https://expressjs.com/en/api.html#res). Refer to their API reference for other uses of responses.
@@ -0,0 +1,135 @@
export const metadata = {
title: `${pageNumber} Request Body Parameter Validation`,
}
# {metadata.title}
In this chapter, you'll learn how to validate request body parameters in your custom API route.
## Example Scenario
Consider you're creating a `POST` API route at `/custom`. It accepts two paramters `a` and `b` that are required numbers, and returns their sum.
The next steps explain how to add validation to this API route, as an example.
---
## Step 1: Create Zod Schema
Medusa uses [Zod](https://zod.dev/) to validate the body parameters of an incoming request.
To use Zod to validate your custom schemas, create a `validators.ts` file in any `src/api` subfolder. This file holds Zod schemas for each of your API routes.
For example, create the file `src/api/custom/validators.ts` with the following content:
```ts title="src/api/custom/validators.ts"
import { z } from "zod"
export const PostStoreCustomSchema = z.object({
a: z.number(),
b: z.number(),
})
```
The `PostStoreCustomSchema` variable is a Zod schema that indicates the request body is valid if:
1. It's an object.
2. It has a property `a` that is a required number.
3. It has a property `b` that is a required number.
---
## Step 2: Add Validation Middleware
To use this schema for validating the body parameters of requests to `/custom`, use the `validateAndTransformBody` middleware provided by `@medusajs/framework/utils`. It accepts the Zod schema as a parameter.
For example, create the file `src/api/middlewares.ts` with the following content:
```ts title="src/api/middlewares.ts"
import { defineMiddlewares } from "@medusajs/medusa"
import {
validateAndTransformBody,
} from "@medusajs/framework/utils"
import { PostStoreCustomSchema } from "./custom/validators"
export default defineMiddlewares({
routes: [
{
matcher: "/custom",
method: "POST",
middlewares: [
validateAndTransformBody(PostStoreCustomSchema),
],
},
],
})
```
This applies the `validateAndTransformBody` middleware on `POST` requests to `/custom`. It uses the `PostStoreCustomSchema` as the validation schema.
### How the Validation Works
If a request's body parameters don't pass the validation, the `validateAndTransformBody` middleware throws an error indicating the validation errors.
If a request's body parameters are validated successfully, the middleware sets the validated body parameters in the `validatedBody` property of `MedusaRequest`.
---
## Step 3: Use Validated Body in API Route
In your API route, consume the validated body using the `validatedBody` property of `MedusaRequest`.
For example, create the file `src/api/custom/route.ts` with the following content:
export const routeHighlights = [
["5", "PostStoreCustomSchemaType", "Infer the request body type from the schema to pass it as a type parameter to `MedusaRequest`."],
["14", "", "Access the body parameters using `validatedBody`."]
]
```ts title="src/api/custom/route.ts" highlights={routeHighlights}
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { z } from "zod"
import { PostStoreCustomSchema } from "./validators"
type PostStoreCustomSchemaType = z.infer<
typeof PostStoreCustomSchema
>
export const POST = async (
req: MedusaRequest<PostStoreCustomSchemaType>,
res: MedusaResponse
) => {
res.json({
sum: req.validatedBody.a + req.validatedBody.b,
})
}
```
In the API route, you use the `validatedBody` property of `MedusaRequest` to access the values of the `a` and `b` properties.
<Note title="Tip">
To pass the request body's type as a type parameter to `MedusaRequest`, use Zod's `infer` type that accepts the type of a schema as a parameter.
</Note>
---
## Test it Out
To test out the validation, send a `POST` request to `/custom`. You can try sending incorrect request body parameters.
For example, if you omit the `a` parameter, you'll receive a `400` response code with the following response data:
```json
{
"type": "invalid_data",
"message": "Invalid request: Field 'a' is required"
}
```
---
## Learn More About Validation Schemas
To see different examples and learn more about creating a validation schema, refer to [Zod's documentation](https://zod.dev).
@@ -0,0 +1,33 @@
export const metadata = {
title: `${pageNumber} Architectural Modules`,
}
# {metadata.title}
In this chapter, youll learn about architectural modules.
## What is an Architectural Module?
An architectural module implements features and mechanisms related to the Medusa applications architecture and infrastructure.
Since modules are interchangeable, you have more control over Medusas architecture. For example, you can choose to use Memcached for event handling instead of Redis.
---
## Architectural Module Types
There are different architectural module types including:
![Diagram illustrating how the modules connect to third-party services](https://res.cloudinary.com/dza7lstvk/image/upload/v1727095814/Medusa%20Book/architectural-modules_bj9bb9.jpg)
- Cache Module: Defines the caching mechanism or logic to cache computational results.
- Event Module: Integrates a pub/sub service to handle subscribing to and emitting events.
- Workflow Engine Module: Integrates a service to store and track workflow executions and steps.
- File Module: Integrates a storage service to handle uploading and managing files.
- Notification Module: Integrates a third-party service or defines custom logic to send notifications to users and customers.
---
## Architectural Modules List
Refer to the [Architectural Modules reference](!resources!/architectural-modules) for a list of Medusas architectural modules, available modules to install, and how to create an architectural module.
@@ -0,0 +1,58 @@
export const metadata = {
title: `${pageNumber} Medusa's Architecture`,
}
# {metadata.title}
In this chapter, you'll learn about the architectural layers in Medusa.
## HTTP, Workflow, and Module Layers
Medusa is a headless commerce platform. So, storefronts, admin dashboards, and other clients consume Medusa's functionalities through its API routes.
In a common Medusa application, requests go through four layers in the stack. In order of entry, those are:
1. API Routes (HTTP): Our API Routes are the typical entry point.
2. Workflows: API Routes consume workflows that hold the opinionated business logic of your application.
3. Modules: Workflows use domain-specific modules for resource management.
3. Data store: Modules query the underlying datastore, which is a PostgreSQL database in common cases.
![Diagram illustrating the HTTP layer](https://res.cloudinary.com/dza7lstvk/image/upload/v1727175296/Medusa%20Book/http-layer_sroafr.jpg)
---
## Database Layer
The Medusa application injects into each module a connection to the configured PostgreSQL database.
Modules use that connection to read and write data to the database.
![Diagram illustrating the database layer](https://res.cloudinary.com/dza7lstvk/image/upload/v1727175379/Medusa%20Book/db-layer_pi7tix.jpg)
---
## Service Integrations
Third-party services are integrated through commerce and architectural modules.
You also create custom third-party integrations through a custom module.
### Commerce Modules
Commerce modules integrate third-party services relevant for commerce or user-facing features. For example, you integrate Stripe through a payment module provider.
![Diagram illustrating the commerce modules integration to third-party services](https://res.cloudinary.com/dza7lstvk/image/upload/v1727175357/Medusa%20Book/service-commerce_qcbdsl.jpg)
### Architectural Modules
Architectural modules integrate third-party services and systems for architectural features. For example, you integrate Redis as a pub/sub service to send events, or SendGrid to send notifications.
![Diagram illustrating the architectural modules integration to third-party services and systems](https://res.cloudinary.com/dza7lstvk/image/upload/v1727175342/Medusa%20Book/service-arch_ozvryw.jpg)
---
## Full Diagram of Medusa's Architecture
The following diagram illustrates Medusa's architecture over the three layers.
![Full diagram illustrating Medusa's architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1727174897/Medusa%20Book/architectural-diagram-full.jpg)
@@ -0,0 +1,72 @@
export const metadata = {
title: `${pageNumber} Custom CLI Scripts`,
}
# {metadata.title}
In this chapter, you'll learn how create and execute custom scripts from Medusa's CLI tool.
## What is a Custom CLI Script?
A custom CLI script is a function to execute through Medusa's CLI tool. This is useful when creating custom Medusa tooling to run through the CLI.
---
## How to Create a Custom CLI Script?
To create a custom CLI script, create a TypeScript or JavaScript file under the `src/scripts` directory. The file must default export a function.
For example, create the file `src/scripts/my-script.ts` with the following content:
```ts title="src/scripts/my-script.ts"
import {
ExecArgs,
IProductModuleService,
} from "@medusajs/framework/types"
import { Modules } from "@medusajs/framework/utils"
export default async function myScript({ container }: ExecArgs) {
const productModuleService: IProductModuleService = container.resolve(
Modules.PRODUCT
)
const [, count] = await productModuleService
.listAndCountProducts()
console.log(`You have ${count} product(s)`)
}
```
The function receives as a parameter an object having a `container` property, which is an instance of the Medusa Container. Use it to resolve resources in your Medusa application.
---
## How to Run Custom CLI Script?
To run the custom CLI script, run the Medusa CLI's `exec` command:
```bash
npx medusa exec ./src/scripts/my-script.ts
```
---
## Custom CLI Script Arguments
Your script can accept arguments from the command line. Arguments are passed to the function's object parameter in the `args` property.
For example:
```ts
import { ExecArgs } from "@medusajs/framework/types"
export default async function myScript({ args }: ExecArgs) {
console.log(`The arguments you passed: ${args}`)
}
```
Then, pass the arguments in the `exec` command after the file path:
```bash
npx medusa exec ./src/scripts/my-script.ts arg1 arg2
```
@@ -0,0 +1,200 @@
export const metadata = {
title: `${pageNumber} Seed Data with Custom CLI Script`,
}
# {metadata.title}
In this chapter, you'll learn how to seed data using a custom CLI script.
## How to Seed Data
To seed dummy data for development or demo purposes, use a custom CLI script.
In the CLI script, use your custom workflows or Medusa's existing workflows, which you can browse in [this reference](!resources!/medusa-workflows-reference), to seed data.
### Example: Seed Dummy Products
In this section, you'll follow an example of creating a custom CLI script that seeds fifty dummy products.
First, install the [Faker](https://fakerjs.dev/) library to generate random data in your script:
```bash npm2yarn
npm install --save-dev @faker-js/faker
```
Then, create the file `src/scripts/demo-products.ts` with the following content:
export const highlights = [
["16", "salesChannelModuleService", "Resolve the Sales Chanel Module's main service"],
["19", "logger", "Resolve the logger to log messages in the terminal."],
["22", "query", "Resolve Query to retrieve data later."],
["26", "defaultSalesChannel", "Retrieve the default sales channel to associate products with."],
["31", "sizeOptions", "Declare the size options to be used in the products' variants."],
["32", "colorOptions", "Declare the color options to be used in the products' variants."],
["33", "currency_code", "Declare the currency code to use in products' prices."],
["34", "productsNum", "The number of products to seed."]
]
```ts title="src/scripts/demo-products.ts" highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
import { ExecArgs } from "@medusajs/framework/types"
import { faker } from "@faker-js/faker"
import {
ContainerRegistrationKeys,
Modules,
ProductStatus,
} from "@medusajs/framework/utils"
import {
createInventoryLevelsWorkflow,
createProductsWorkflow,
} from "@medusajs/medusa/core-flows"
export default async function seedDummyProducts({
container,
}: ExecArgs) {
const salesChannelModuleService = container.resolve(
Modules.SALES_CHANNEL
)
const logger = container.resolve(
ContainerRegistrationKeys.LOGGER
)
const query = container.resolve(
ContainerRegistrationKeys.QUERY
)
const defaultSalesChannel = await salesChannelModuleService
.listSalesChannels({
name: "Default Sales Channel",
})
const sizeOptions = ["S", "M", "L", "XL"]
const colorOptions = ["Black", "White"]
const currency_code = "eur"
const productsNum = 50
// TODO seed products
}
```
So far, in the script, you:
- Resolve the Sales Channel Module's main service to retrieve the application's default sales channel. This is the sales channel the dummy products will be available in.
- Resolve the Logger to log messages in the terminal, and Query to later retrieve data useful for the seeded products.
- Initialize some default data to use when seeding the products next.
Next, replace the `TODO` with the following:
```ts title="src/scripts/demo-products.ts"
const productsData = new Array(productsNum).fill(0).map((_, index) => {
const title = faker.commerce.product() + "_" + index
return {
title,
is_giftcard: true,
description: faker.commerce.productDescription(),
status: ProductStatus.PUBLISHED,
options: [
{
title: "Size",
values: sizeOptions,
},
{
title: "Color",
values: colorOptions,
},
],
images: [
{
url: faker.image.urlPlaceholder({
text: title,
}),
},
{
url: faker.image.urlPlaceholder({
text: title,
}),
},
],
variants: new Array(10).fill(0).map((_, variantIndex) => ({
title: `${title} ${variantIndex}`,
sku: `variant-${variantIndex}${index}`,
prices: new Array(10).fill(0).map((_, priceIndex) => ({
currency_code,
amount: 10 * priceIndex,
})),
options: {
Size: sizeOptions[Math.floor(Math.random() * 3)],
},
})),
sales_channels: [
{
id: defaultSalesChannel[0].id,
},
],
}
})
// TODO seed products
```
You generate fifty products using the sales channel and variables you initialized, and using Faker for random data, such as the product's title or images.
Then, replace the new `TODO` with the following:
```ts title="src/scripts/demo-products.ts"
const { result: products } = await createProductsWorkflow(container).run({
input: {
products: productsData,
},
})
logger.info(`Seeded ${products.length} products.`)
// TODO add inventory levels
```
You create the generated products using the `createProductsWorkflow` imported previously from `@medusajs/medusa/core-flows`. It accepts the product data as input, and returns the created products.
Only thing left is to create inventory levels for the products. So, replace the last `TODO` with the following:
```ts title="src/scripts/demo-products.ts"
logger.info("Seeding inventory levels.")
const { data: stockLocations } = await query.graph({
entity: "stock_location",
fields: ["id"],
})
const { data: inventoryItems } = await query.graph({
entity: "inventory_item",
fields: ["id"],
})
const inventoryLevels = inventoryItems.map((inventoryItem) => ({
location_id: stockLocations[0].id,
stocked_quantity: 1000000,
inventory_item_id: inventoryItem.id,
}))
await createInventoryLevelsWorkflow(container).run({
input: {
inventory_levels: inventoryLevels,
},
})
logger.info("Finished seeding inventory levels data.")
```
You use Query to retrieve the stock location, to use the first location in the application, and the inventory items.
Then, you generate inventory levels for each inventory item, associating it with the first stock location.
Finally, you use the `createInventoryLevelsWorkflow` imported from `@medusajs/medusa/core-flows` to create the inventory levels.
### Test Script
To test out the script, run the following command in your project's directory:
```bash
npx medusa exec ./src/scripts/demo-products.ts
```
This seeds the products to your database. If you run your Medusa application and view the products in the dashboard, you'll find fifty new products.
@@ -0,0 +1,84 @@
export const metadata = {
title: `${pageNumber} Configure Data Model Properties`,
}
# {metadata.title}
In this chapter, youll learn how to configure data model properties.
## Propertys Default Value
Use the `default` method on a property's definition to specify the default value of a property.
For example:
export const defaultHighlights = [
["6", "default", "Set the default value to `black`."],
["9", "default", "Set the default value to `0`."]
]
```ts highlights={defaultHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
color: model
.enum(["black", "white"])
.default("black"),
age: model
.number()
.default(0),
// ...
})
export default MyCustom
```
In this example, you set the default value of the `color` enum property to `black`, and that of the `age` number property to `0`.
---
## Nullable Property
Use the `nullable` method to indicate that a propertys value can be `null`.
For example:
export const nullableHighlights = [
["4", "nullable", "Configure the `price` property to allow `null` values."]
]
```ts highlights={nullableHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
price: model.bigNumber().nullable(),
// ...
})
export default MyCustom
```
---
## Unique Property
The `unique` method indicates that a propertys value must be unique in the database through a unique index.
For example:
export const uniqueHighlights = [
["4", "unique", "Configure the `email` property to allow unique values only."]
]
```ts highlights={uniqueHighlights}
import { model } from "@medusajs/framework/utils"
const User = model.define("user", {
email: model.text().unique(),
// ...
})
export default User
```
In this example, multiple users cant have the same email.
@@ -0,0 +1,13 @@
export const metadata = {
title: `${pageNumber} Data Model Default Properties`,
}
# {metadata.title}
In this chapter, you'll learn about the properties available by default in your data model.
When you create a data model, the following properties are created for you by Medusa:
- `created_at`: A `dateTime` property that stores when a record of the data model was created.
- `updated_at`: A `dateTime` property that stores when a record of the data model was updated.
- `deleted_at`: A `dateTime` property that stores when a record of the data model was deleted. When you soft-delete a record, Medusa sets the `deleted_at` property to the current date.
@@ -0,0 +1,160 @@
export const metadata = {
title: `${pageNumber} Data Model Database Index`,
}
# {metadata.title}
In this chapter, youll learn how to define a database index on a data model.
## Define Database Index on Property
Use the `index` method on a property's definition to define a database index.
For example:
export const highlights = [
["5", "index", "Define an index on the `name` property."],
["6", '"IDX_MY_CUSTOM_NAME"', "Index name is optional."]
]
```ts highlights={highlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
name: model.text().index(
"IDX_MY_CUSTOM_NAME"
),
})
export default MyCustom
```
The `index` method optionally accepts the name of the index as a parameter.
In this example, you define an index on the `name` property.
---
## Define Database Index on Data Model
A data model has an `indexes` method that defines database indices on its properties.
The index can be on multiple columns (composite index). For example:
export const dataModelIndexHighlights = [
["7", "indexes", "Define indices on the data model's properties."],
["9", "on", "Specify the properties to define the index on."]
]
```ts highlights={dataModelIndexHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
name: model.text(),
age: model.number(),
}).indexes([
{
on: ["name", "age"],
},
])
export default MyCustom
```
The `indexes` method receives an array of indices as a parameter. Each index is an object with a required `on` property indicating the properties to apply the index on.
In the above example, you define a composite index on the `name` and `age` properties.
### Index Conditions
An index can have conditions. For example:
export const conditionHighlights = [
["10", "where", "Specify conditions on properties."],
["11", "", "Create the index when `age` is `30`."]
]
```ts highlights={conditionHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
name: model.text(),
age: model.number(),
}).indexes([
{
on: ["name", "age"],
where: {
age: 30,
},
},
])
export default MyCustom
```
The index object passed to `indexes` accepts a `where` property whose value is an object of conditions. The object's key is a property's name, and its value is the condition on that property.
In the example above, the composite index is created on the `name` and `age` properties when the `age`'s value is `30`.
A property's condition can be a negation. For example:
export const negationHighlights = [
["12", "", "Create the index when `age` is not `null`."]
]
```ts highlights={negationHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
name: model.text(),
age: model.number().nullable(),
}).indexes([
{
on: ["name", "age"],
where: {
age: {
$ne: null,
},
},
},
])
export default MyCustom
```
A property's value in `where` can be an object having a `$ne` property. `$ne`'s value indicates what the specified property's value shouldn't be.
In the example above, the composite index is created on the `name` and `age` properties when `age`'s value is not `null`.
### Unique Database Index
The object passed to `indexes` accepts a `unique` property indicating that the created index must be a unique index.
For example:
export const uniqueHighlights = [
["10", "unique", "Specify if the index is a unique index."]
]
```ts highlights={uniqueHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
name: model.text(),
age: model.number(),
}).indexes([
{
on: ["name", "age"],
unique: true,
},
])
export default MyCustom
```
This creates a unique composite index on the `name` and `age` properties.
@@ -0,0 +1,42 @@
export const metadata = {
title: `${pageNumber} Infer Type of Data Model`,
}
# {metadata.title}
In this chapter, you'll learn how to infer the type of a data model.
## How to Infer Type of Data Model?
Consider you have a `MyCustom` data model. You can't reference this data model in a type, such as a workflow input or service method output types, since it's a variable.
Instead, Medusa provides an `InferTypeOf` utility imported from `@medusajs/framework/types` that transforms your data model to a type.
For example:
```ts
import { InferTypeOf } from "@medusajs/framework/types"
import { MyCustom } from "../models/my-custom" // relative path to the model
export type MyCustom = InferTypeOf<typeof MyCustom>
```
The `InferTypeOf` utility accepts as a type argument the type of the data model.
Since the `MyCustom` data model is a variable, use the `typeof` operator to pass the data model as a type argument to `InferTypeOf`.
You can now use the `MyCustom` type to reference a data model in other types, such as in workflow inputs or service method outputs:
```ts title="Example Service"
// other imports...
import { InferTypeOf } from "@medusajs/framework/types"
import { MyCustom } from "../models/my-custom"
type MyCustom = InferTypeOf<typeof MyCustom>
class HelloModuleService extends MedusaService({ MyCustom }) {
async doSomething(): Promise<MyCustom> {
// ...
}
}
```
@@ -0,0 +1,202 @@
import { BetaBadge } from "docs-ui"
export const metadata = {
title: `${pageNumber} Manage Relationships`,
}
# {metadata.title} <BetaBadge tooltipText="Data model relationships are in active development and may change." text="Beta" />
In this chapter, you'll learn how to manage relationships between data models when creating, updating, or retrieving records using the module's main service.
## Manage One-to-One Relationship
### BelongsTo Side of One-to-One
When you create a record of a data model that belongs to another through a one-to-one relation, pass the ID of the other data model's record in the relation property.
For example, assuming you have the [User and Email data models from the previous chapter](../relationships/page.mdx#one-to-one-relationship), set an email's user ID as follows:
export const belongsHighlights = [
["4", "user", "The ID of the user the email belongs to."],
["11", "user", "The ID of the user the email belongs to."]
]
```ts highlights={belongsHighlights}
// when creating an email
const email = await helloModuleService.createEmails({
// other properties...
user: "123",
})
// when updating an email
const email = await helloModuleService.updateEmails({
id: "321",
// other properties...
user: "123",
})
```
In the example above, you pass the `user` property when creating or updating an email to specify the user it belongs to.
### HasOne Side
When you create a record of a data model that has one of another, pass the ID of the other data model's record in the relation property.
For example, assuming you have the [User and Email data models from the previous chapter](../relationships/page.mdx#one-to-one-relationship), set an user's email ID as follows:
export const hasOneHighlights = [
["4", "email", "The ID of the email that the user has."],
["11", "email", "The ID of the email that the user has."]
]
```ts highlights={hasOneHighlights}
// when creating a user
const user = await helloModuleService.createUsers({
// other properties...
email: "123",
})
// when updating a user
const user = await helloModuleService.updateUsers({
id: "321",
// other properties...
email: "123",
})
```
In the example above, you pass the `email` property when creating or updating a user to specify the email it has.
---
## Manage One-to-Many Relationship
In a one-to-many relationship, you can only manage the associations from the `belongsTo` side.
When you create a record of the data model on the `belongsTo` side, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
For example, assuming you have the [Product and Store data models from the previous chapter](../relationships/page.mdx#one-to-many-relationship), set a product's store ID as follows:
export const manyBelongsHighlights = [
["4", "store_id", "The ID of the store the product belongs to."],
["11", "store_id", "The ID of the store the product belongs to."]
]
```ts highlights={manyBelongsHighlights}
// when creating a product
const product = await helloModuleService.createProducts({
// other properties...
store_id: "123",
})
// when updating a product
const product = await helloModuleService.updateProducts({
id: "321",
// other properties...
store_id: "123",
})
```
In the example above, you pass the `store_id` property when creating or updating a product to specify the store it belongs to.
---
## Manage Many-to-Many Relationship
### Create Associations
When you create a record of a data model that has a many-to-many relationship to another data model, pass an array of IDs of the other data model's records in the relation property.
For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), set the association between products and orders as follows:
export const manyHighlights = [
["4", "orders", "The IDs of the orders associated with the product."],
["11", "products", "The IDs of the products associated with the order."]
]
```ts highlights={manyHighlights}
// when creating a product
const product = await helloModuleService.createProducts({
// other properties...
orders: ["123", "321"],
})
// when creating an order
const order = await helloModuleService.createOrders({
id: "321",
// other properties...
products: ["123", "321"],
})
```
In the example above, you pass the `orders` property when you create a product, and you pass the `products` property when you create an order.
### Update Associations
When you use the `update` methods generated by the service factory, you also pass an array of IDs as the relation property's value to add new associated records.
However, this removes any existing associations to records whose IDs aren't included in the array.
For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), you update the product's related orders as so:
```ts
const product = await helloModuleService.updateProducts({
id: "123",
// other properties...
orders: ["321"],
})
```
If the product was associated with an order, and you don't include that order's ID in the `orders` array, the association between the product and order is removed.
So, to add a new association without removing existing ones, retrieve the product first to pass its associated orders when updating the product:
export const updateAssociationHighlights = [
["1", "retrieveProduct", "Retrieve the product with its orders."],
["12", "", "Pass the IDs of the orders previously associated with the product."],
["13", "", "Associate the product with a new order."]
]
```ts highlights={updateAssociationHighlights}
const product = await helloModuleService.retrieveProduct(
"123",
{
relations: ["orders"],
}
)
const updatedProduct = await helloModuleService.updateProducts({
id: product.id,
// other properties...
orders: [
...product.orders.map((order) => order.id),
"321",
],
})
```
This keeps existing associations between the product and orders, and adds a new one.
---
## Retrieve Records of Relation
The `list`, `listAndCount`, and `retrieve` methods of a module's main service accept as a second parameter an object of options.
To retrieve the records associated with a data model's records through a relationship, pass in the second parameter object a `relations` property whose value is an array of relationship names.
For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), you retrieve a product's orders as follows:
export const retrieveHighlights = [
["4", `"orders"`, "Retrieve the records associated with the product\nthrough the `orders` relationship."]
]
```ts highlights={retrieveHighlights}
const product = await helloModuleService.retrieveProducts(
"123",
{
relations: ["orders"],
}
)
```
In the example above, the retrieved product has an `orders` property, whose value is an array of orders associated with the product.
@@ -0,0 +1,15 @@
export const metadata = {
title: `${pageNumber} Data Models Advanced Guides`,
}
# {metadata.title}
In the next chapters, you'll learn more about defining data models.
You'll learn about:
- The different property types available.
- How to set a property as a primary key.
- How to create and manage relationships.
- How to configure properties, such as making them nullable or searchable.
- How to manually write migrations.
@@ -0,0 +1,30 @@
export const metadata = {
title: `${pageNumber} Data Models Primary Key`,
}
# {metadata.title}
In this chapter, youll learn how to configure the primary key of a data model.
## primaryKey Method
To set any `id`, `text`, or `number` property as a primary key, use the `primaryKey` method.
For example:
export const highlights = [
["4", "primaryKey", "Define the `id` property to be the data model's primary key."]
]
```ts highlights={highlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id().primaryKey(),
// ...
})
export default MyCustom
```
In the example above, the `id` property is defined as the data model's primary key.
@@ -0,0 +1,204 @@
export const metadata = {
title: `${pageNumber} Data Model Property Types`,
}
# {metadata.title}
In this chapter, youll learn about the types of properties in a data models schema.
These types are available as methods on the `model` utility imported from `@medusajs/framework/utils`.
## id
The `id` method defines an automatically generated string ID property. The generated ID is a unique string that has a mix of letters and numbers.
For example:
export const idHighlights = [["4", ".id()", "Define an `id` property."]]
```ts highlights={idHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
id: model.id(),
// ...
})
export default MyCustom
```
---
## text
The `text` method defines a string property.
For example:
export const textHighlights = [["4", "text", "Define a `text` property."]]
```ts highlights={textHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
name: model.text(),
// ...
})
export default MyCustom
```
---
## number
The `number` method defines a number property.
For example:
export const numberHighlights = [["4", "number", "Define a `number` property."]]
```ts highlights={numberHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
age: model.number(),
// ...
})
export default MyCustom
```
---
## bigNumber
The `bigNumber` method defines a number property that expects large numbers, such as prices.
For example:
export const bigNumberHighlights = [["4", "bigNumber", "Define a `bigNumber` property."]]
```ts highlights={bigNumberHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
price: model.bigNumber(),
// ...
})
export default MyCustom
```
---
## boolean
The `boolean` method defines a boolean property.
For example:
export const booleanHighlights = [["4", "boolean", "Define a `boolean` property."]]
```ts highlights={booleanHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
hasAccount: model.boolean(),
// ...
})
export default MyCustom
```
---
### enum
The `enum` method defines a property whose value can only be one of the specified values.
For example:
export const enumHighlights = [["4", "enum", "Define a `enum` property."]]
```ts highlights={enumHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
color: model.enum(["black", "white"]),
// ...
})
export default MyCustom
```
The `enum` method accepts an array of possible string values.
---
## dateTime
The `dateTime` method defines a timestamp property.
For example:
export const dateTimeHighlights = [["4", "dateTime", "Define a `dateTime` property."]]
```ts highlights={dateTimeHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
date_of_birth: model.dateTime(),
// ...
})
export default MyCustom
```
---
## json
The `json` method defines a property whose value is a stringified JSON object.
For example:
export const jsonHighlights = [["4", "json", "Define a `json` property."]]
```ts highlights={jsonHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
metadata: model.json(),
// ...
})
export default MyCustom
```
---
## array
The `array` method defines an array of strings property.
For example:
export const arrHightlights = [["4", "array", "Define an `array` property."]]
```ts highlights={arrHightlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
names: model.array(),
// ...
})
export default MyCustom
```
---
## Properties Reference
Refer to the [Data Model API reference](https://docs.medusajs.com/v2/resources/references/data-model) for a full reference of the properties.
@@ -0,0 +1,252 @@
import { BetaBadge } from "docs-ui"
export const metadata = {
title: `${pageNumber} Data Model Relationships`,
}
# {metadata.title} <BetaBadge text="Beta" tooltipText="Data model relationships are in active development and may change." />
In this chapter, youll learn how to define relationships between data models in your module.
## What is a Relationship Property?
A relationship property defines an association in the database between two models. It's created using methods on the `models` utility, such as `hasOne` or `belongsTo`.
When you generate a migration for these data models, the migrations include foreign key columns or pivot tables, based on the relationship's type.
<Note title="Use data model relationships when" type="success">
You want to create a relation between data models in the same module.
</Note>
<Note title="Don't use data model relationships if" type="error">
You want to create a relationship between data models in different modules. Use module links instead.
</Note>
---
## One-to-One Relationship
A one-to-one relationship indicates that one record of a data model belongs to or is associated with another.
To define a one-to-one relationship, create relationship properties in the data models using the following methods:
1. `hasOne`: indicates that the model has one record of the specified model.
2. `belongsTo`: indicates that the model belongs to one record of the specified model.
For example:
export const oneToOneHighlights = [
["5", "hasOne", "A user has one email."],
["10", "belongsTo", "An email belongs to a user."],
["11", `"email"`, "The relationship's name in the `User` data model."]
]
```ts highlights={oneToOneHighlights}
import { model } from "@medusajs/framework/utils"
const User = model.define("user", {
id: model.id().primaryKey(),
email: model.hasOne(() => Email),
})
const Email = model.define("email", {
id: model.id().primaryKey(),
user: model.belongsTo(() => User, {
mappedBy: "email",
}),
})
```
In the example above, a user has one email, and an email belongs to one user.
The `hasOne` and `belongsTo` methods accept a function as a first parameter. The function returns the associated data model.
The `belongsTo` method also requires passing as a second parameter an object with the property `mappedBy`. Its value is the name of the relationship property in the other data model.
### Optional Relationship
To make the relationship optional on the `hasOne` or `belongsTo` side, use the `nullable` method on either properties as explained in [this chapter](../configure-properties/page.mdx#nullable-property).
### One-to-One Relationship in the Database
When you generate the migrations of data models that have a one-to-one relationship, the migration adds to the table of the data model that has the `belongsTo` property:
1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `email` table will have a `user_id` column.
2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
![Diagram illustrating the relation between user and email records in the database](https://res.cloudinary.com/dza7lstvk/image/upload/v1726733492/Medusa%20Book/one-to-one_cj5np3.jpg)
---
## One-to-Many Relationship
A one-to-many relationship indicates that one record of a data model has many records of another data model.
To define a one-to-many relationship, create relationship properties in the data models using the following methods:
1. `hasMany`: indicates that the model has more than one records of the specified model.
2. `belongsTo`: indicates that the model belongs to one record of the specified model.
For example:
export const oneToManyHighlights = [
["5", "hasMany", "A store has many products"],
["10", "belongsTo", "A product has one store."],
["11", `"products"`, "The relationship's name in the `Store` data model."]
]
```ts highlights={oneToManyHighlights}
import { model } from "@medusajs/framework/utils"
const Store = model.define("store", {
id: model.id().primaryKey(),
products: model.hasMany(() => Product),
})
const Product = model.define("product", {
id: model.id().primaryKey(),
store: model.belongsTo(() => Store, {
mappedBy: "products",
}),
})
```
In this example, a store has many products, but a product belongs to one store.
### Optional Relationship
To make the relationship optional on the `belongsTo` side, use the `nullable` method on the property as explained in [this chapter](../configure-properties/page.mdx#nullable-property).
### One-to-Many Relationship in the Database
When you generate the migrations of data models that have a one-to-many relationship, the migration adds to the table of the data model that has the `belongsTo` property:
1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `product` table will have a `store_id` column.
2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
![Diagram illustrating the relation between a store and product records in the database](https://res.cloudinary.com/dza7lstvk/image/upload/v1726733937/Medusa%20Book/one-to-many_d6wtcw.jpg)
---
## Many-to-Many Relationship
A many-to-many relationship indicates that many records of a data model can be associated to many records of another data model.
To define a many-to-many relationship, create relationship properties in the data models using the `manyToMany` method.
For example:
export const manyToManyHighlights = [
["5", "manyToMany", "An order is associated with many products."],
["12", "manyToMany", "A product is associated with many orders."]
]
```ts highlights={manyToManyHighlights}
import { model } from "@medusajs/framework/utils"
const Order = model.define("order", {
id: model.id().primaryKey(),
products: model.manyToMany(() => Product, {
mappedBy: "orders",
}),
})
const Product = model.define("product", {
id: model.id().primaryKey(),
orders: model.manyToMany(() => Order, {
mappedBy: "products",
}),
})
```
At least one side of the many-to-many relationship must have the `mappedBy` property set in the second object parameter of the `manyToMany` object. Its value is the name of the relationship property in the other data model.
In this example, an order is associated with many products, and a product is associated with many orders.
### Many-to-Many Relationship in the Database
When you generate the migrations of data models that have a many-to-many relationship, the migration adds a new pivot table.
The pivot table has a column with the name `{data_model}_id` for each of the data model's tables. It also has foreign keys on each of these columns to their respective tables.
![Diagram illustrating the relation between order and product records in the database](https://res.cloudinary.com/dza7lstvk/image/upload/v1726734269/Medusa%20Book/many-to-many_fzy5pq.jpg)
---
## Set Relationship Name in the Other Model
The relationship property methods accept as a second parameter an object of options. The `mappedBy` property defines the name of the relationship in the other data model.
This is useful if the relationship propertys name is different than that of the associated data model.
As seen in previous examples, the `mappedBy` option is required for the `belongsTo` method.
For example:
export const relationNameHighlights = [
["6", `"owner"`, "The relationship's name in the `Email` data model."],
["13", `"email"`, "The relationship's name in the `User` data model."]
]
```ts highlights={relationNameHighlights}
import { model } from "@medusajs/framework/utils"
const User = model.define("user", {
id: model.id().primaryKey(),
email: model.hasOne(() => Email, {
mappedBy: "owner",
}),
})
const Email = model.define("email", {
id: model.id().primaryKey(),
owner: model.belongsTo(() => User, {
mappedBy: "email",
}),
})
```
In this example, you specify in the `User` data models relationship property that the name of the relationship in the `Email` data model is `owner`.
---
## Cascades
When an operation is performed on a data model, such as record deletion, the relationship cascade specifies what related data model records should be affected by it.
For example, if a store is deleted, its products should also be deleted.
The `cascades` method used on a data model configures which child records an operation is cascaded to.
For example:
export const highlights = [
["8", "", "When a store is deleted, delete its associated products."]
]
```ts highlights={highlights}
import { model } from "@medusajs/framework/utils"
const Store = model.define("store", {
id: model.id().primaryKey(),
products: model.hasMany(() => Product),
})
.cascades({
delete: ["products"],
})
const Product = model.define("product", {
id: model.id().primaryKey(),
store: model.belongsTo(() => Store, {
mappedBy: "products",
}),
})
```
The `cascades` method accepts an object. Its key is the operations name, such as `delete`. The value is an array of relationship property names that the operation is cascaded to.
In the example above, when a store is deleted, its associated products are also deleted.
@@ -0,0 +1,50 @@
export const metadata = {
title: `${pageNumber} Searchable Data Model Property`,
}
# {metadata.title}
In this chapter, you'll learn what a searchable property is and how to define it.
## What is a Searchable Property?
Methods generated by the [service factory](../../modules/service-factory/page.mdx) that accept filters, such as `list{ModelName}s`, accept a `q` property as part of the filters.
When the `q` filter is passed, the data model's searchable properties are queried to find matching records.
---
## Define a Searchable Property
Use the `searchable` method on a `text` property to indicate that it's searchable.
For example:
export const searchableHighlights = [
["4", "searchable", "Define the `name` property as searchable."]
]
```ts highlights={searchableHighlights}
import { model } from "@medusajs/framework/utils"
const MyCustom = model.define("my_custom", {
name: model.text().searchable(),
// ...
})
export default MyCustom
```
In this example, the `name` property is searchable.
### Search Example
If you pass a `q` filter to the `listMyCustoms` method:
```ts
const myCustoms = await helloModuleService.listMyCustoms({
q: "John",
})
```
This retrieves records that include `John` in their `name` property.
@@ -0,0 +1,70 @@
export const metadata = {
title: `${pageNumber} Write Migration`,
}
# {metadata.title}
In this chapter, you'll learn how to create a migration and write it manually.
## What is a Migration?
A migration is a class created in a TypeScript or JavaScript file under a module's `migrations` directory. It has two methods:
- The `up` method reflects changes on the database.
- The `down` method reverts the changes made in the `up` method.
---
## How to Write a Migration?
The Medusa CLI tool provides a [db:generate](!resources!/medusa-cli/commands/db#dbgenerate) command to generate a migration for the specified modules' data models.
Alternatively, you can manually create a migration file under the `migrations` directory of your module.
For example:
```ts title="src/modules/hello/migrations/Migration20240429.ts"
import { Migration } from "@mikro-orm/migrations"
export class Migration20240702105919 extends Migration {
async up(): Promise<void> {
this.addSql("create table if not exists \"my_custom\" (\"id\" text not null, \"name\" text not null, \"created_at\" timestamptz not null default now(), \"updated_at\" timestamptz not null default now(), \"deleted_at\" timestamptz null, constraint \"my_custom_pkey\" primary key (\"id\"));")
}
async down(): Promise<void> {
this.addSql("drop table if exists \"my_custom\" cascade;")
}
}
```
The migration's file name should be of the format `Migration{YEAR}{MONTH}{DAY}.ts`. The migration class in the file extends the `Migration` class imported from `@mikro-orm/migrations`.
In the `up` and `down` method of the migration class, you use the `addSql` method provided by MikroORM's `Migration` class to run PostgreSQL syntax.
In the example above, the `up` method creates the table `my_custom`, and the `down` method drops the table if the migration is reverted.
<Note title="Tip">
Refer to [MikroORM's documentation](https://mikro-orm.io/docs/migrations#migration-class) for more details on writing migrations.
</Note>
---
## Run the Migration
To run your migration, run the following command:
<Note>
This command also syncs module links. If you don't want that, use the `--skip-links` option.
</Note>
```bash
npx medusa db:migrate
```
This reflects the changes in the database as implemented in the migration's `up` method.
@@ -0,0 +1,69 @@
import { TypeList } from "docs-ui"
export const metadata = {
title: `${pageNumber} Event Data Payload`,
}
# {metadata.title}
In this chapter, you'll learn how subscribers receive an event's data payload.
## Access Event's Data Payload
When events are emitted, theyre emitted with a data payload.
The object that the subscriber function receives as a parameter has an `event` property, which is an object holding the event payload in a `data` property with additional context.
For example:
export const highlights = [
["7", "event", "The event details."],
["8", "{ id: string }", "The type of expected data payloads."],
]
```ts title="src/subscribers/product-created.ts" highlights={highlights} collapsibleLines="1-5" expandButtonLabel="Show Imports"
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
export default async function productCreateHandler({
event,
}: SubscriberArgs<{ id: string }>) {
const productId = event.data.id
console.log(`The product ${productId} was created`)
}
export const config: SubscriberConfig = {
event: "product.created",
}
```
The `event` object has the following properties:
<TypeList types={[
{
name: "data",
type: "`object`",
description: "The data payload of the event. Its properties are different for each event."
},
{
name: "name",
type: "string",
description: "The name of the triggered event."
},
{
name: "metadata",
type: "`object`",
description: "Additional data and context of the emitted event.",
optional: true
},
]} sectionTitle="Access Event's Data Payload" />
This logs the product ID received in the `product.created` events data payload to the console.
{/* ---
## List of Events with Data Payload
Refer to [this reference](!resources!/events-reference) for a full list of events emitted by Medusa and their data payloads. */}
@@ -0,0 +1,48 @@
export const metadata = {
title: `${pageNumber} Emit an Event`,
}
# {metadata.title}
In this chapter, you'll learn how to emit an event in a workflow.
## Emit Event Step
Medusa provides an `emitEventStep` helper step in the `@medusajs/medusa/core-flows` package that emits an event.
When you emit an event, you specify the event's name and data payload to pass with the event.
For example:
export const highlights = [
["13", "emitEventStep", "Emit an event."],
["14", `"custom.created"`, "The name of the event to emit."],
["15", "data", "The data payload to pass with the event."]
]
```ts highlights={highlights}
import {
createWorkflow,
} from "@medusajs/framework/workflows-sdk"
import {
emitEventStep,
} from "@medusajs/medusa/core-flows"
const helloWorldWorkflow = createWorkflow(
"hello-world",
() => {
// ...
emitEventStep({
eventName: "custom.created",
data: {
id: "123",
},
})
}
)
```
In this example, you emit the event `custom.created` and pass in the data payload an ID property.
If you execute the workflow, the emit is emitted and any subscribers listening to the event are executed.
@@ -0,0 +1,174 @@
export const metadata = {
title: `${pageNumber} Add Columns to a Link`,
}
# {metadata.title}
In this chapter, you'll learn how to add custom columns to a link definition and manage them.
## How to Add Custom Columns to a Link's Table?
The `defineLink` function used to define a link accepts a third paramter, which is an object of options.
To add custom columns to a link's table, pass in the third parameter of `defineLink` a `database` property:
export const linkHighlights = [
["10", "extraColumns", "Custom columns to add to the created link's table."],
["11", "metadata", "The column's name."],
["12", "type", "The column's type."]
]
```ts highlights={linkHighlights}
import HelloModule from "../modules/hello"
import ProductModule from "@medusajs/medusa/product"
import { defineLink } from "@medusajs/framework/utils"
export default defineLink(
ProductModule.linkable.product,
HelloModule.linkable.myCustom,
{
database: {
extraColumns: {
metadata: {
type: "json",
},
},
},
}
)
```
This adds to the table created for the link between `product` and `myCustom` a `metadata` column of type `json`.
### Database Options
The `database` property defines configuration for the table created in the database.
Its `extraColumns` property defines custom columns to create in the link's table.
`extraColumns`'s value is an object whose keys are the names of the columns, and values are the column's configurations as an object.
### Column Configurations
The column's configurations object accepts the following properties:
- `type`: The column's type. Possible values are:
- `string`
- `text`
- `integer`
- `boolean`
- `date`
- `time`
- `datetime`
- `enum`
- `json`
- `array`
- `enumArray`
- `float`
- `double`
- `decimal`
- `bigint`
- `mediumint`
- `smallint`
- `tinyint`
- `blob`
- `uuid`
- `uint8array`
- `defaultValue`: The column's default value.
- `nullable`: Whether the column can have `null` values.
---
## Set Custom Column when Creating Link
The object you pass to the remote link's `create` method accepts a `data` property. Its value is an object whose keys are custom column names, and values are the value of the custom column for this link.
For example:
<Note>
Learn more about the remote link, how to resolve it, and its methods in [this chapter](../remote-link/page.mdx).
</Note>
```ts
await remoteLink.create({
[Modules.PRODUCT]: {
product_id: "123",
},
HELLO_MODULE: {
my_custom_id: "321",
},
data: {
metadata: {
test: true,
},
},
})
```
---
## Retrieve Custom Column with Link
To retrieve linked records with their custom columns, use Query and pass the link definition as the `entity` property's value.
For example:
<Note>
Learn more about Query and how to resolve use it [this chapter](../remote-link/page.mdx).
</Note>
export const retrieveHighlights = [
["1", "productHelloLink", "Import the exported link definition."],
["6", "entity", "Pass the link definition to retrieve its data."],
["7", `"metadata"`, "Retrieve the `metadata` column."],
["7", `"product.*"`, "Retrieve the linked product's details."],
["7", `"my_custom.*"`, "Retrieve the linked `myCustom` record's details."],
]
```ts highlights={retrieveHighlights}
import productHelloLink from "../links/product-hello"
// ...
const { data } = await query.graph({
entity: productHelloLink.entryPoint,
fields: ["metadata", "product.*", "my_custom.*"],
filters: {
product_id: "prod_123",
},
})
```
This retrieves the product of id `prod_123` and its linked `my_custom` records.
In the `fields` array you pass `metadata`, which is the custom column to retrieve of the link.
---
## Update Custom Column's Value
The remote link's `create` method updates a link's data if the link between the specified records already exists.
So, to update the value of a custom column in a created link, use the `create` method again passing it a new value for the custom column.
For example:
```ts
await remoteLink.create({
[Modules.PRODUCT]: {
product_id: "123",
},
HELLO_MODULE: {
my_custom_id: "321",
},
data: {
metadata: {
test: false,
},
},
})
```
@@ -0,0 +1,61 @@
export const metadata = {
title: `${pageNumber} Module Link Direction`,
}
# {metadata.title}
In this chapter, you'll learn about the difference in module link directions, and which to use based on your use case.
## Link Direction
The module link's direction depends on the order you pass the data model configuration parameters to `defineLink`.
For example, the following defines a link from the `helloModuleService`'s `myCustom` data model to the Product Module's `product` data model:
```ts
export default defineLink(
HelloModule.linkable.myCustom,
ProductModule.linkable.product
)
```
Whereas the following defines a link from the Product Module's `product` data model to the `helloModuleService`'s `myCustom` data model:
```ts
export default defineLink(
ProductModule.linkable.product,
HelloModule.linkable.myCustom
)
```
The above links are two different links that serve different purposes.
---
## Which Link Direction to Use?
### Extend Data Models
If you're adding a link to a data model to extend it and add new fields, define the link from the main data model to the custom data model.
For example, if the `myCustom` data model adds new fields to the `product` data model, define the link from `product` to `myCustom`:
```ts
export default defineLink(
ProductModule.linkable.product,
HelloModule.linkable.myCustom
)
```
### Associate Data Models
If you're linking data models to indicate an association between them, define the link from the custom data model to the main data model.
For example, if the `myCustom` data model is associated to the `product` data model, define the link from `myCustom` to `product`:
```ts
export default defineLink(
HelloModule.linkable.myCustom,
ProductModule.linkable.product
)
```
@@ -0,0 +1,143 @@
export const metadata = {
title: `${pageNumber} Module Link`,
}
# {metadata.title}
In this chapter, youll learn what a module link is.
## What is a Module Link?
Since modules are isolated, you can't access another module's data models to add a relation to it or extend it.
Instead, you use a module link. A module link forms an association between two data models of different modules, while maintaining module isolation.
---
## How to Define a Module Link?
### 1. Create Link File
Links are defined in a TypeScript or JavaScript file under the `src/links` directory. The file defines the link using the `defineLink` function imported from `@medusajs/framework/utils` and exports it.
For example:
export const highlights = [
["6", "linkable", "Special `linkable` property that holds the linkable data models of `HelloModule`."],
["7", "linkable", "Special `linkable` property that holds the linkable data models of `ProductModule`."],
]
```ts title="src/links/hello-product.ts" highlights={highlights}
import HelloModule from "../modules/hello"
import ProductModule from "@medusajs/medusa/product"
import { defineLink } from "@medusajs/framework/utils"
export default defineLink(
ProductModule.linkable.product,
HelloModule.linkable.myCustom
)
```
The `defineLink` function accepts as parameters the link configurations of each module's data model. A module has a special `linkable` property that holds these configurations for its data models.
In this example, you define a module link between the `hello` module's `MyCustom` data model and the Product Module's `Product` data model.
### 2. Sync Links
After defining the link, run the `db:sync-links` command:
```bash
npx medusa db:sync-links
```
The Medusa application creates a new table for your link to store the IDs of linked records.
Use this command whenever you make changes to your links. For example, run this command if you remove your link definition file.
<Note title="Tip">
You can also use the `db:migrate` command, which both runs the migrations and syncs the links.
</Note>
---
## How Module Links Work?
When you define a module link, the Medusa application creates a table in the database for that link.
Then, when you create links between records of the data models, the IDs of these data models are stored as a new record in the link's table.
![Diagram illustration for links](https://res.cloudinary.com/dza7lstvk/image/upload/v1726482168/Medusa%20Book/Custom_Link_Illustration_fsisfa.jpg)
---
## When to Use Module Links
<Note title="Use module links when" type="success">
- You want to create a relation between data models from different modules.
- You want to extend the data model of another module.
</Note>
<Note title="Don't use module links if" type="error">
You want to create a relationship between data models in the same module. Use data model relationships instead.
</Note>
---
## Define a List Link
By default, the defined link establishes a one-to-one relation: a record of a data model is linked to one record of the other data model.
To specify that a data model can have multiple of its records linked to the other data model's record, use the `isList` option.
For example:
```ts
import HelloModule from "../modules/hello"
import ProductModule from "@medusajs/medusa/product"
import { defineLink } from "@medusajs/framework/utils"
export default defineLink(
ProductModule.linkable.product,
{
linkable: HelloModule.linkable.myCustom,
isList: true,
}
)
```
In this case, you pass an object of configuration as a parameter instead. The object accepts the following properties:
- `linkable`: The data model's link configuration.
- `isList`: Whether multiple records can be linked to one record of the other data model.
In this example, a record of `product` can be linked to more than one record of `myCustom`.
---
## Set Delete Cascades on Link
To enable delete cascade on a link so that when a record is deleted, its linked records are also deleted, pass the `deleteCascades` property in the object passed to `defineLink`.
For example:
```ts
import HelloModule from "../modules/hello"
import ProductModule from "@medusajs/medusa/product"
import { defineLink } from "@medusajs/framework/utils"
export default defineLink(
ProductModule.linkable.product,
{
linkable: HelloModule.linkable.myCustom,
deleteCascades: true,
}
)
```
In this example, when a product is deleted, its linked `myCustom` record is also deleted.
@@ -0,0 +1,229 @@
import { TypeList, Tabs, TabsList, TabsTriggerVertical, TabsContent, TabsContentWrapper } from "docs-ui"
export const metadata = {
title: `${pageNumber} Query`,
}
# {metadata.title}
In this chapter, youll learn about the Query utility and how to use it to fetch data from modules.
<Note type="soon" title="In Development">
Query is in development and is subject to change in future releases.
</Note>
## What is Query?
Query fetches data across modules. Its a set of methods registered in the Medusa container under the `query` key.
In your resources, such as API routes or workflows, you can resolve Query to fetch data across custom modules and Medusas commerce modules.
---
## Query Example
For example, create the route `src/api/query/route.ts` with the following content:
export const exampleHighlights = [
["13", "", "Resolve Query from the Medusa container."],
["15", "graph", "Run a query to retrieve data."],
["16", "entity", "The name of the data model you're querying."],
["17", "fields", "An array of the data models properties to retrieve in the result."],
]
```ts title="src/api/query/route.ts" highlights={exampleHighlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
import {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import {
ContainerRegistrationKeys,
} from "@medusajs/framework/utils"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
const { data: myCustoms } = await query.graph({
entity: "my_custom",
fields: ["id", "name"],
})
res.json({ my_customs: myCustoms })
}
```
In the above example, you resolve Query from the Medusa container using the `ContainerRegistrationKeys.QUERY` (`query`) key.
Then, you run a query using its `graph` method. This method accepts as a parameter an object with the following required properties:
- `entity`: The data model's name, as specified in the first parameter of the `model.define` method used for the data model's definition.
- `fields`: An array of the data models properties to retrieve in the result.
The method returns an object that has a `data` property, which holds an array of the retrieved data. For example:
```json title="Returned Data"
{
"data": [
{
"id": "123",
"name": "test"
}
]
}
```
---
## Querying the Graph
When you use the `query.graph` method, you're running a query through an internal graph that the Medusa application creates.
This graph collects data models of all modules in your application, including commerce and custom modules, and identifies relations and links between them.
---
## Retrieve Linked Records
Retrieve the records of a linked data model by passing in `fields` the data model's name suffixed with `.*`.
For example:
```ts highlights={[["6"]]}
const { data: myCustoms } = await query.graph({
entity: "my_custom",
fields: [
"id",
"name",
"product.*",
],
})
```
<Note title="Tip">
`.*` means that all of data model's properties should be retrieved. To retrieve a specific property, replace the `*` with the property's name. For example, `product.title`.
</Note>
### Retrieve List Link Records
If the linked data model has `isList` enabled in the link definition, pass in `fields` the data model's plural name suffixed with `.*`.
For example:
```ts highlights={[["6"]]}
const { data: myCustoms } = await query.graph({
entity: "my_custom",
fields: [
"id",
"name",
"products.*",
],
})
```
---
## Apply Filters
```ts highlights={[["6"], ["7"], ["8"], ["9"]]}
const { data: myCustoms } = await query.graph({
entity: "my_custom",
fields: ["id", "name"],
filters: {
id: [
"mc_01HWSVWR4D2XVPQ06DQ8X9K7AX",
"mc_01HWSVWK3KYHKQEE6QGS2JC3FX",
],
},
})
```
The `query.graph` function accepts a `filters` property. You can use this property to filter retrieved records.
In the example above, you filter the `my_custom` records by multiple IDs.
<Note>
Filters don't apply on fields of linked data models from other modules.
</Note>
---
## Sort Records
```ts highlights={[["5"], ["6"], ["7"]]}
const { data: myCustoms } = await query.graph({
entity: "my_custom",
fields: ["id", "name"],
pagination: {
order: {
name: "DESC",
},
},
})
```
<Note>
Sorting doesn't work on fields of linked data models from other modules.
</Note>
The `graph` method's object parameter accepts a `pagination` property to configure the pagination of retrieved records.
To sort returned records, pass an `order` property to `pagination`.
The `order` property is an object whose keys are property names, and values are either:
- `ASC` to sort records by that property in ascending order.
- `DESC` to sort records by that property in descending order.
---
## Apply Pagination
```ts highlights={[["8", "skip", "The number of records to skip before fetching the results."], ["9", "take", "The number of records to fetch."]]}
const {
data: myCustoms,
metadata: { count, take, skip },
} = await query.graph({
entity: "my_custom",
fields: ["id", "name"],
pagination: {
skip: 0,
take: 10,
},
})
```
To paginate the returned records, pass the following properties to `pagination`:
- `skip`: (required to apply pagination) The number of records to skip before fetching the results.
- `take`: The number of records to fetch.
When you provide the pagination fields, the `query.graph` method's returned object has a `metadata` property. Its value is an object having the following properties:
<TypeList types={[
{
name: "skip",
type: "`number`",
description: "The number of records skipped."
},
{
name: "take",
type: "`number`",
description: "The number of records requested to fetch."
},
{
name: "count",
type: "`number`",
description: "The total number of records."
}
]} sectionTitle="Apply Pagination" />
@@ -0,0 +1,153 @@
import { BetaBadge } from "docs-ui"
export const metadata = {
title: `${pageNumber} Remote Link`,
}
# {metadata.title} <BetaBadge text="Beta" tooltipText="Remote Links are in active development." />
In this chapter, youll learn what the remote link is and how to use it to manage links.
## What is the Remote Link?
The remote link is a class with utility methods to manage links between data models. Its registered in the Medusa container under the `remoteLink` registration name.
For example:
```ts collapsibleLines="1-9" expandButtonLabel="Show Imports"
import {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import {
ContainerRegistrationKeys,
} from "@medusajs/framework/utils"
import {
RemoteLink,
} from "@medusajs/framework/modules-sdk"
export async function POST(
req: MedusaRequest,
res: MedusaResponse
): Promise<void> {
const remoteLink: RemoteLink = req.scope.resolve(
ContainerRegistrationKeys.REMOTE_LINK
)
// ...
}
```
You can use its methods to manage links, such as create or delete links.
---
## Create Link
To create a link between records of two data models, use the `create` method of the remote link.
For example:
```ts
import { Modules } from "@medusajs/framework/utils"
// ...
await remoteLink.create({
[Modules.PRODUCT]: {
product_id: "prod_123",
},
"helloModuleService": {
my_custom_id: "mc_123",
},
})
```
The `create` method accepts as a parameter an object. The objects keys are the names of the linked modules.
<Note title="Important">
The keys (names of linked modules) must be in the same direction of the link definition.
</Note>
The value of each modules 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.
---
## Dismiss Link
To remove a link between records of two data models, use the `dismiss` method of the remote link.
For example:
```ts
import { Modules } from "@medusajs/framework/utils"
// ...
await remoteLink.dismiss({
[Modules.PRODUCT]: {
product_id: "prod_123",
},
"helloModuleService": {
my_custom_id: "mc_123",
},
})
```
The `dismiss` method accepts the same parameter type as the [create method](#create-link).
<Note title="Important">
The keys (names of linked modules) must be in the same direction of the link definition.
</Note>
---
## Cascade Delete Linked Records
If a record is deleted, use the `delete` method of the remote link to delete all linked records.
For example:
```ts
import { Modules } from "@medusajs/framework/utils"
// ...
await productModuleService.deleteVariants([variant.id])
await remoteLink.delete({
[Modules.PRODUCT]: {
product_id: "prod_123",
},
})
```
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:
```ts
import { Modules } from "@medusajs/framework/utils"
// ...
await productModuleService.restoreProducts(["prod_123"])
await remoteLink.restore({
[Modules.PRODUCT]: {
product_id: "prod_123",
},
})
```
@@ -0,0 +1,70 @@
export const metadata = {
title: `${pageNumber} Module's Container`,
}
# {metadata.title}
In this chapter, you'll learn about the module's container and how to resolve resources in that container.
## Module's Container
Since modules are isolated, each module has a local container only used by the resources of that module.
So, resources in the module, such as services or loaders, can only resolve other resources registered in the module's container.
### List of Registered Resources
Find a list of resources or dependencies registered in a module's container in [this Learning Resources reference](!resoures!/medusa-container-resources).
---
## Resolve Resources
### Services
A service's constructor accepts as a first parameter an object used to resolve resources registered in the module's container.
For example:
```ts highlights={[["4"], ["10"]]}
import { Logger } from "@medusajs/framework/types"
type InjectedDependencies = {
logger: Logger
}
export default class HelloModuleService {
protected logger_: Logger
constructor({ logger }: InjectedDependencies) {
this.logger_ = logger
this.logger_.info("[HelloModuleService]: Hello World!")
}
// ...
}
```
### Loader
A loader function accepts as a parameter an object having the property `container`. Its value is the module's container used to resolve resources.
For example:
```ts highlights={[["9"]]}
import {
LoaderOptions,
} from "@medusajs/framework/types"
import {
ContainerRegistrationKeys
} from "@medusajs/framework/utils"
export default async function helloWorldLoader({
container,
}: LoaderOptions) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
logger.info("[helloWorldLoader]: Hello, World!")
}
```
@@ -0,0 +1,464 @@
import { CodeTabs, CodeTab } from "docs-ui"
export const metadata = {
title: `${pageNumber} Perform Database Operations in a Service`,
}
# {metadata.title}
In this chapter, you'll learn how to perform database operations in a module's service.
<Note>
This chapter is intended for more advanced database use-cases where you need more control over queries and operations. For basic database operations, such as creating or retrieving data of a model, use the [Service Factory](../service-factory/page.mdx) instead.
</Note>
## Run Queries
[MikroORM's entity manager](https://mikro-orm.io/docs/entity-manager) is a class that has methods to run queries on the database and perform operations.
Medusa provides an `InjectManager` decorator imported from `@medusajs/utils` that injects a service's method with a [forked entity manager](https://mikro-orm.io/docs/identity-map#forking-entity-manager).
So, to run database queries in a service:
1. Add the `InjectManager` decorator to the method.
2. Add as a last parameter an optional `sharedContext` parameter that has the `MedusaContext` decorator imported from `@medusajs/utils`. This context holds database-related context, including the manager injected by `InjectManager`
For example, in your service, add the following methods:
export const methodsHighlight = [
["11", "getCount", "Retrieves the number of records in `my_custom` using the `count` method."],
["18", "getCountSql", "Retrieves the number of records in `my_custom` using the `execute` method."]
]
```ts highlights={methodsHighlight}
// other imports...
import {
InjectManager,
MedusaContext,
} from "@medusajs/framework/utils"
class HelloModuleService {
// ...
@InjectManager()
async getCount(
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<number> {
return await sharedContext.manager.count("my_custom")
}
@InjectManager()
async getCountSql(
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<number> {
const data = await sharedContext.manager.execute(
"SELECT COUNT(*) as num FROM my_custom"
)
return parseInt(data[0].num)
}
}
```
You add two methods `getCount` and `getCountSql` that have the `InjectManager` decorator. Each of the methods also accept the `sharedContext` parameter which has the `MedusaContext` decorator.
The entity manager is injected to the `sharedContext.manager` property, which is an instance of [EntityManager from the @mikro-orm/knex package](https://mikro-orm.io/api/5.9/knex/class/EntityManager).
You use the manager in the `getCount` method to retrieve the number of records in a table, and in the `getCountSql` to run a PostgreSQL query that retrieves the count.
<Note>
Refer to [MikroORM's reference](https://mikro-orm.io/api/5.9/knex/class/EntityManager) for a full list of the entity manager's methods.
</Note>
---
## Execute Operations in Transactions
To wrap database operations in a transaction, you create two methods:
1. A private or protected method that's wrapped in a transaction. To wrap it in a transaction, you use the `InjectTransactionManager` decorator imported from `@medusajs/utils`.
2. A public method that calls the transactional method. You use on it the `InjectManager` decorator as explained in the previous section.
Both methods must accept as a last parameter an optional `sharedContext` parameter that has the `MedusaContext` decorator imported from `@medusajs/utils`. It holds database-related contexts passed through the Medusa application.
For example:
export const opHighlights = [
["11", "InjectTransactionManager", "A decorator that injects the a transactional entity manager into the `sharedContext` parameter."],
["17", "MedusaContext", "A decorator to use Medusa's shared context."],
["20", "nativeUpdate", "Update a record."],
["31", "execute", "Retrieve the updated record."],
["38", "InjectManager", "A decorator that injects a forked entity manager into the context."],
]
```ts highlights={opHighlights}
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
} from "@medusajs/framework/utils"
import { Context } from "@medusajs/framework/types"
import { EntityManager } from "@mikro-orm/knex"
class HelloModuleService {
// ...
@InjectTransactionManager()
protected async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
const transactionManager = sharedContext.transactionManager
await transactionManager.nativeUpdate(
"my_custom",
{
id: input.id,
},
{
name: input.name,
}
)
// retrieve again
const updatedRecord = await transactionManager.execute(
`SELECT * FROM my_custom WHERE id = '${input.id}'`
)
return updatedRecord
}
@InjectManager()
async update(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
) {
return await this.update_(input, sharedContext)
}
}
```
The `HelloModuleService` has two methods:
- A protected `update_` that performs the database operations inside a transaction.
- A public `update` that executes the transactional protected method.
The shared context's `transactionManager` property holds the transactional entity manager (injected by `InjectTransactionManager`) that you use to perform database operations.
<Note>
Refer to [MikroORM's reference](https://mikro-orm.io/api/5.9/knex/class/EntityManager) for a full list of the entity manager's methods.
</Note>
### Why Wrap a Transactional Method
The variables in the transactional method (for example, `update_`) hold values that are uncomitted to the database. They're only committed once the method finishes execution.
So, if in your method you perform database operations, then use their result to perform other actions, such as connect to a third-party service, you'll be working with uncommitted data.
By placing only the database operations in a method that has the `InjectTransactionManager` and using it in a wrapper method, the wrapper method receives the committed result of the transactional method.
<Note title="Optimization Tip">
This is also useful if you perform heavy data normalization outside of the database operations. In that case, you don't hold the transaction for a longer time than needed.
</Note>
For example, the `update` method could be changed to the following:
```ts
// other imports...
import { EntityManager } from "@mikro-orm/knex"
class HelloModuleService {
// ...
@InjectManager()
async update(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
) {
const newData = await this.update_(input, sharedContext)
await sendNewDataToSystem(newData)
return newData
}
}
```
In this case, only the `update_` method is wrapped in a transaction. The returned value `newData` holds the committed result, which can be used for other operations, such as passed to a `sendNewDataToSystem` method.
### Using Methods in Transactional Methods
If your transactional method uses other methods that accept a Medusa context, pass the shared context to those method.
For example:
```ts
// other imports...
import { EntityManager } from "@mikro-orm/knex"
class HelloModuleService {
// ...
@InjectTransactionManager()
protected async anotherMethod(
@MedusaContext() sharedContext?: Context<EntityManager>
) {
// ...
}
@InjectTransactionManager()
protected async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
anotherMethod(sharedContext)
}
}
```
You use the `anotherMethod` transactional method in the `update_` transactional method, so you pass it the shared context.
The `anotherMethod` now runs in the same transaction as the `update_` method.
---
## Configure Transactions
To configure the transaction, such as its [isolation level](https://www.postgresql.org/docs/current/transaction-iso.html), use the `baseRepository` dependency registered in your module's container.
The `baseRepository` is an instance of a repository class that provides methods to create transactions, run database operations, and more.
The `baseRepository` has a `transaction` method that allows you to run a function within a transaction and configure that transaction.
For example, resolve the `baseRepository` in your service's constructor:
<CodeTabs group="service-type">
<CodeTab label="Extending Service Factory" value="service-factory">
```ts highlights={[["14"]]}
import { MedusaService } from "@medusajs/framework/utils"
import MyCustom from "./models/my-custom"
import { DAL } from "@medusajs/framework/types"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
}
class HelloModuleService extends MedusaService({
MyCustom,
}){
protected baseRepository_: DAL.RepositoryService
constructor({ baseRepository }: InjectedDependencies) {
super(...arguments)
this.baseRepository_ = baseRepository
}
}
export default HelloModuleService
```
</CodeTab>
<CodeTab label="Without Service Factory" value="no-service-factory">
```ts highlights={[["10"]]}
import { DAL } from "@medusajs/framework/types"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
}
class HelloModuleService {
protected baseRepository_: DAL.RepositoryService
constructor({ manager }: InjectedDependencies) {
this.baseRepository_ = baseRepository
}
}
export default HelloModuleService
```
</CodeTab>
</CodeTabs>
Then, add the following method that uses it:
export const repoHighlights = [
["20", "transaction", "Wrap the function parameter in a transaction."]
]
```ts highlights={repoHighlights}
// ...
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
} from "@medusajs/framework/utils"
import { Context } from "@medusajs/framework/types"
import { EntityManager } from "@mikro-orm/knex"
class HelloModuleService {
// ...
@InjectTransactionManager()
protected async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
return await this.baseRepository_.transaction(
async (transactionManager) => {
await transactionManager.nativeUpdate(
"my_custom",
{
id: input.id,
},
{
name: input.name,
}
)
// retrieve again
const updatedRecord = await transactionManager.execute(
`SELECT * FROM my_custom WHERE id = '${input.id}'`
)
return updatedRecord
},
{
transaction: sharedContext.transactionManager,
}
)
}
@InjectManager()
async update(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
) {
return await this.update_(input, sharedContext)
}
}
```
The `update_` method uses the `baseRepository_.transaction` method to wrap a function in a transaction.
The function parameter receives a transactional entity manager as a parameter. Use it to perform the database operations.
The `baseRepository_.transaction` method also receives as a second parameter an object of options. You must pass in it the `transaction` property and set its value to the `sharedContext.transactionManager` property so that the function wrapped in the transaction uses the injected transaction manager.
<Note>
Refer to [MikroORM's reference](https://mikro-orm.io/api/5.9/knex/class/EntityManager) for a full list of the entity manager's methods.
</Note>
### Transaction Options
The second parameter of the `baseRepository_.transaction` method is an object of options that accepts the following properties:
1. `transaction`: Set the transactional entity manager passed to the function. You must provide this option as explained in the previous section.
```ts highlights={[["16"]]}
// other imports...
import { EntityManager } from "@mikro-orm/knex"
class HelloModuleService {
// ...
@InjectTransactionManager()
async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
return await this.baseRepository_.transaction<EntityManager>(
async (transactionManager) => {
// ...
},
{
transaction: sharedContext.transactionManager,
}
)
}
}
```
2. `isolationLevel`: Sets the transaction's [isolation level](https://www.postgresql.org/docs/current/transaction-iso.html). Its values can be:
- `read committed`
- `read uncommitted`
- `snapshot`
- `repeatable read`
- `serializable`
```ts highlights={[["19"]]}
// other imports...
import { IsolationLevel } from "@mikro-orm/core"
class HelloModuleService {
// ...
@InjectTransactionManager()
async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
return await this.baseRepository_.transaction<EntityManager>(
async (transactionManager) => {
// ...
},
{
isolationLevel: IsolationLevel.READ_COMMITTED,
}
)
}
}
```
3. `enableNestedTransactions`: (default: `false`) whether to allow using nested transactions.
- If `transaction` is provided and this is disabled, the manager in `transaction` is re-used.
```ts highlights={[["16"]]}
class HelloModuleService {
// ...
@InjectTransactionManager()
async update_(
input: {
id: string,
name: string
},
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<any> {
return await this.baseRepository_.transaction<EntityManager>(
async (transactionManager) => {
// ...
},
{
enableNestedTransactions: false,
}
)
}
}
```
@@ -0,0 +1,113 @@
export const metadata = {
title: `${pageNumber} Module Isolation`,
}
# {metadata.title}
In this chapter, you'll learn how modules are isolated, and what that means for your custom development.
<Note title="Summary">
- Modules can't access resources, such as services or data models, from other modules.
- Use Medusa's linking concepts, as explained in the [Module Links chapters](../../module-links/page.mdx), to extend a module's data models and retrieve data across modules.
</Note>
## How are Modules Isolated?
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.
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.
---
## Why are Modules Isolated
Some of the module isolation's benefits include:
- Integrate your module into any Medusa application without side-effects to your setup.
- Replace existing modules with your custom implementation, if your use case is drastically different.
- Use modules in other environments, such as Edge functions and Next.js apps.
---
## How to Extend Data Model of Another Module?
To extend the data model of another module, such as the `product` data model of the Product Module, use Medusa's linking concepts as explained in the [Module Links chapters](../../module-links/page.mdx).
---
## How to Use Services of Other Modules?
If you're building a feature that uses functionalities from different modules, use a workflow whose steps resolve the modules' services to perform these functionalities.
Workflows ensure data consistency through their roll-back mechanism and tracking of each execution's status, steps, input, and output.
### Example
For example, consider you have two modules:
1. A module that stores and manages brands in your application.
2. A module that integrates a third-party Content Management System (CMS).
To sync brands from your application to the third-party system, create the following steps:
export const stepsHighlights = [
["1", "retrieveBrandsStep", "A step that retrieves brands using a brand module."],
["14", "createBrandsInCmsStep", "A step that creates brands using a CMS module."],
["25", "", "Add a compensation function to the step if an error occurs."]
]
```ts title="Example Steps" highlights={stepsHighlights}
const retrieveBrandsStep = createStep(
"retrieve-brands",
async (_, { container }) => {
const brandModuleService = container.resolve(
"brandModuleService"
)
const brands = await brandModuleService.listBrands()
return new StepResponse(brands)
}
)
const createBrandsInCmsStep = createStep(
"create-brands-in-cms",
async ({ brands }, { container }) => {
const cmsModuleService = container.resolve(
"cmsModuleService"
)
const cmsBrands = await cmsModuleService.createBrands(brands)
return new StepResponse(cmsBrands, cmsBrands)
},
async (brands, { container }) => {
const cmsModuleService = container.resolve(
"cmsModuleService"
)
await cmsModuleService.deleteBrands(
brands.map((brand) => brand.id)
)
}
)
```
The `retrieveBrandsStep` retrieves the brands from a brand module, and the `createBrandsInCmsStep` creates the brands in a third-party system using a CMS module.
Then, create the following workflow that uses these steps:
```ts title="Example Workflow"
export const syncBrandsWorkflow = createWorkflow(
"sync-brands",
() => {
const brands = retrieveBrandsStep()
updateBrandsInCmsStep({ brands })
}
)
```
You can then use this workflow in an API route, scheduled job, or other resources that use this functionality.
@@ -0,0 +1,130 @@
export const metadata = {
title: `${pageNumber} Multiple Services in a Module`,
}
# {metadata.title}
In this chapter, you'll learn how to use multiple services in a module.
## Module's Main and Internal Services
A module has one main service only, which is the service exported in the module's definition.
However, you may use other services in your module to better organize your code or split functionalities. These are called internal services that can be resolved within your module, but not in external resources.
---
## How to Add an Internal Service
### 1. Create Service
To add an internal service, create it in the `services` directory of your module.
For example, create the file `src/modules/hello/services/client.ts` with the following content:
```ts title="src/modules/hello/services/client.ts"
export class ClientService {
async getMessage(): Promise<string> {
return "Hello, World!"
}
}
```
### 2. Export Service in Index
Next, create an `index.ts` file under the `services` directory of the module that exports your internal services.
For example, create the file `src/modules/hello/services/index.ts` with the following content:
```ts title="src/modules/hello/services/index.ts"
export * from "./client"
```
This exports the `ClientService`.
### 3. Resolve Internal Service
Internal services exported in the `services/index.ts` file of your module are now registered in the container and can be resolved in other services in the module as well as loaders.
For example, in your main service:
```ts title="src/modules/hello/service.ts" highlights={[["5"], ["13"]]}
// other imports...
import { ClientService } from "./services"
type InjectedDependencies = {
clientService: ClientService
}
class HelloModuleService extends MedusaService({
MyCustom,
}){
protected clientService_: ClientService
constructor({ clientService }: InjectedDependencies) {
super(...arguments)
this.clientService_ = clientService
}
}
```
You can now use your internal service in your main service.
---
## Resolve Resources in Internal Service
Resolve dependencies from your module's container in the constructor of your internal service.
For example:
```ts
import { Logger } from "@medusajs/framework/types"
type InjectedDependencies = {
logger: Logger
}
export class ClientService {
protected logger_: Logger
constructor({ logger }: InjectedDependencies) {
this.logger_ = logger
}
}
```
---
## Access Module Options
Your internal service can't access the module's options.
To retrieve the module's options, use the `configModule` registered in the module's container, which is the configurations in `medusa-config.ts`.
For example:
```ts
import { ConfigModule } from "@medusajs/framework/types"
import { HELLO_MODULE } from ".."
export type InjectedDependencies = {
configModule: ConfigModule
}
export class ClientService {
protected options: Record<string, any>
constructor({ configModule }: InjectedDependencies) {
const moduleDef = configModule.modules[HELLO_MODULE]
if (typeof moduleDef !== "boolean") {
this.options = moduleDef.options
}
}
}
```
The `configModule` has a `modules` property that includes all registered modules. Retrieve the module's configuration using its registration key.
If its value is not a `boolean`, set the service's options to the module configuration's `options` property.
@@ -0,0 +1,100 @@
export const metadata = {
title: `${pageNumber} Module Options`,
}
# {metadata.title}
In this chapter, youll learn about passing options to your module from the Medusa applications configurations and using them in the modules resources.
## What are Module Options?
A module can receive options to customize or configure its functionality.
For example, if youre creating a module that integrates a third-party service, youll want to receive the integration credentials in the options rather than adding them directly in your code.
---
## How to Pass Options to a Module?
To pass options to a module, add an `options` property to the modules configuration in `medusa-config.ts`.
For example:
```js title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
resolve: "./src/modules/hello",
options: {
capitalize: true,
},
},
]
})
```
The `options` propertys value is an object. You can pass any properties you want.
---
## Access Module Options in Main Service
The modules main service receives the module options as a second parameter.
For example:
```ts title="src/modules/hello/service.ts" highlights={[["12"], ["14", "options?: ModuleOptions"], ["17"], ["18"], ["19"]]}
import { MedusaService } from "@medusajs/framework/utils"
import MyCustom from "./models/my-custom"
// recommended to define type in another file
type ModuleOptions = {
capitalize?: boolean
}
export default class HelloModuleService extends MedusaService({
MyCustom,
}){
protected options_: ModuleOptions
constructor({}, options?: ModuleOptions) {
super(...arguments)
this.options_ = options || {
capitalize: false,
}
}
// ...
}
```
---
## Access Module Options in Loader
The object that a modules loaders receive as a parameter has an `options` property holding the module's options.
For example:
```ts title="src/modules/hello/loaders/hello-world.ts" highlights={[["11"], ["12", "ModuleOptions", "The type of expected module options."], ["16"]]}
import {
LoaderOptions,
} from "@medusajs/framework/types"
// recommended to define type in another file
type ModuleOptions = {
capitalize?: boolean
}
export default async function helloWorldLoader({
options,
}: LoaderOptions<ModuleOptions>) {
console.log(
"[HELLO MODULE] Just started the Medusa application!",
options
)
}
```
@@ -0,0 +1,15 @@
export const metadata = {
title: `${pageNumber} Modules Advanced Guides`,
}
# {metadata.title}
In the next chapters, you'll learn more about developing modules and related resources.
By the end of this chapter, you'll know more about:
1. A module's container and how a module is isolated.
2. Passing options to a module.
3. The service factory and the methods it generates.
4. Using a module's service to query and perform actions on the database.
5. Using multiple services in a module.
@@ -0,0 +1,40 @@
export const metadata = {
title: `${pageNumber} Service Constraints`,
}
# {metadata.title}
This chapter lists constraints to keep in mind when creating a service.
## Use Async Methods
Medusa wraps service method executions to inject useful context or transactions. However, since Medusa can't detect whether the method is asynchronus, it always executes methods in the wrapper with the `await` keyword.
For example, if you have a synchronous `getMessage` method, and you use it other resources like workflows, Medusa executes it as an async method:
```ts
await helloModuleService.getMessage()
```
So, make sure your service's methods are always async to avoid unexpected errors or behavior.
```ts highlights={[["8", "", "Method must be async."], ["13", "async", "Correct way of defining the method."]]}
import { MedusaService } from "@medusajs/framework/utils"
import MyCustom from "./models/my-custom"
class HelloModuleService extends MedusaService({
MyCustom,
}){
// Don't
getMessage(): string {
return "Hello, World!"
}
// Do
async getMessage(): Promise<string> {
return "Hello, World!"
}
}
export default HelloModuleService
```
@@ -0,0 +1,299 @@
import { Tabs, TabsContent, TabsContentWrapper, TabsList, TabsTriggerVertical } from "docs-ui"
export const metadata = {
title: `${pageNumber} Service Factory`,
}
# {metadata.title}
In this chapter, youll learn about what the service factory is and how to use it.
## What is the Service Factory?
Medusa provides a service factory that your modules main service can extend.
The service factory generates data management methods for your data models in the database, so you don't have to implement these methods manually.
<Note title="Extend the service factory when" type="success">
Your service provides data-management functionalities of your data models.
</Note>
---
## How to Extend the Service Factory?
Medusa provides the service factory as a `MedusaService` function your service extends. The function creates and returns a service class with generated data-management methods.
For example, create the file `src/modules/hello/service.ts` with the following content:
export const highlights = [
["4", "MedusaService", "The service factory function."],
["5", "MyCustom", "The data models to generate data-management methods for."]
]
```ts title="src/modules/hello/service.ts" highlights={highlights}
import { MedusaService } from "@medusajs/framework/utils"
import MyCustom from "./models/my-custom"
class HelloModuleService extends MedusaService({
MyCustom,
}){
// TODO implement custom methods
}
export default HelloModuleService
```
### MedusaService Parameters
The `MedusaService` function accepts one parameter, which is an object of data models to generate data-management methods for.
In the example above, since the `HelloModuleService` extends `MedusaService`, it has methods to manage the `MyCustom` data model, such as `createMyCustoms`.
### Generated Methods
The service factory generates methods to manage the records of each of the data models provided in the first parameter in the database.
The method's names are the operation's name, suffixed by the data model's key in the object parameter passed to `MedusaService`.
For example, the following methods are generated for the service above:
<Note>
Find a complete reference of each of the methods in [this documentation](!resources!/service-factory-reference)
</Note>
<Tabs defaultValue="listMyCustoms" layoutType="vertical" className="mt-2">
<TabsList>
<TabsTriggerVertical value="listMyCustoms">listMyCustoms</TabsTriggerVertical>
<TabsTriggerVertical value="listAndCountMyCustoms">listAndCount</TabsTriggerVertical>
<TabsTriggerVertical value="retrieveMyCustom">retrieveMyCustom</TabsTriggerVertical>
<TabsTriggerVertical value="createMyCustoms">createMyCustoms</TabsTriggerVertical>
<TabsTriggerVertical value="updateMyCustoms">updateMyCustoms</TabsTriggerVertical>
<TabsTriggerVertical value="deleteMyCustoms">deleteMyCustoms</TabsTriggerVertical>
<TabsTriggerVertical value="softDeleteMyCustoms">softDeleteMyCustoms</TabsTriggerVertical>
<TabsTriggerVertical value="restoreMyCustoms">restoreMyCustoms</TabsTriggerVertical>
</TabsList>
<TabsContentWrapper className="[&_h3]:!mt-0">
<TabsContent value="listMyCustoms">
### listMyCustoms
This method retrieves an array of records based on filters and pagination configurations.
For example:
```ts
const myCustoms = await helloModuleService
.listMyCustoms()
// with filters
const myCustoms = await helloModuleService
.listMyCustoms({
id: ["123"]
})
```
</TabsContent>
<TabsContent value="listAndCountMyCustoms">
### listAndCountMyCustoms
This method retrieves a tuple of an array of records and the total count of available records based on the filters and pagination configurations provided.
For example:
```ts
const [
myCustoms,
count
] = await helloModuleService.listAndCountMyCustoms()
// with filters
const [
myCustoms,
count
] = await helloModuleService.listAndCountMyCustoms({
id: ["123"]
})
```
</TabsContent>
<TabsContent value="retrieveMyCustom">
### retrieveMyCustom
This method retrieves a record by its ID.
For example:
```ts
const myCustom = await helloModuleService
.retrieveMyCustom("123")
```
</TabsContent>
<TabsContent value="createMyCustoms">
### createMyCustoms
This method creates and retrieves records of the data model.
For example:
```ts
const myCustom = await helloModuleService
.createMyCustoms({
name: "test"
})
// create multiple
const myCustoms = await helloModuleService
.createMyCustoms([
{
name: "test"
},
{
name: "test 2"
},
])
```
</TabsContent>
<TabsContent value="updateMyCustoms">
### updateMyCustoms
This method updates and retrieves records of the data model.
For example:
```ts
const myCustom = await helloModuleService
.updateMyCustoms({
id: "123",
name: "test"
})
// update multiple
const myCustoms = await helloModuleService
.updateMyCustoms([
{
id: "123",
name: "test"
},
{
id: "321",
name: "test 2"
},
])
// use filters
const myCustoms = await helloModuleService
.updateMyCustoms([
{
selector: {
id: ["123", "321"]
},
data: {
name: "test"
}
},
])
```
</TabsContent>
<TabsContent value="deleteMyCustoms">
### deleteMyCustoms
This method deletes records by an ID or filter.
For example:
```ts
await helloModuleService.deleteMyCustoms("123")
// delete multiple
await helloModuleService.deleteMyCustoms([
"123", "321"
])
// use filters
await helloModuleService.deleteMyCustoms({
selector: {
id: ["123", "321"]
}
})
```
</TabsContent>
<TabsContent value="softDeleteMyCustoms">
### softDeleteMyCustoms
This method soft-deletes records using an array of IDs or an object of filters.
For example:
```ts
await helloModuleService.softDeleteMyCustoms("123")
// soft-delete multiple
await helloModuleService.softDeleteMyCustoms([
"123", "321"
])
// use filters
await helloModuleService.softDeleteMyCustoms({
id: ["123", "321"]
})
```
</TabsContent>
<TabsContent value="restoreMyCustoms">
### restoreMyCustoms
This method restores soft-deleted records using an array of IDs or an object of filters.
For example:
```ts
await helloModuleService.restoreMyCustoms([
"123", "321"
])
// use filters
await helloModuleService.restoreMyCustoms({
id: ["123", "321"]
})
```
</TabsContent>
</TabsContentWrapper>
</Tabs>
### Using a Constructor
If you implement the `constructor` of your service, make sure to call `super` passing it `...arguments`.
For example:
```ts highlights={[["8"]]}
import { MedusaService } from "@medusajs/framework/utils"
import MyCustom from "./models/my-custom"
class HelloModuleService extends MedusaService({
MyCustom,
}){
constructor() {
super(...arguments)
}
}
export default HelloModuleService
```
@@ -0,0 +1,15 @@
export const metadata = {
title: `${pageNumber} Advanced Development`,
}
# {metadata.title}
In the previous chapters, you got a brief introduction to Medusas basic concepts. However, to build a custom commerce application, you need a deeper understanding of how you utilize these concepts for your business use case.
The next chapters dive deeper into each concept, and explores Medusa's architecture. By the end of these chapters, youll be able to:
- Expose API routes with control over authentication.
- Build sophisticated business logic in modules and manage links between them.
- Create advanced workflows and configure retries and timeout.
- Add new pages to the Medusa Admin.
- Do more with subscribers, scheduled jobs, and other tools.
@@ -0,0 +1,40 @@
export const metadata = {
title: `${pageNumber} Scheduled Jobs Number of Executions`,
}
# {metadata.title}
In this chapter, you'll learn how to set a limit on the number of times a scheduled job is executed.
## numberOfExecutions Option
The export configuration object of the scheduled job accepts an optional property `numberOfExecutions`. Its value is a number indicating how many times the scheduled job can be executed during the Medusa application's runtime.
For example:
export const highlights = [
["9", "numberOfExecutions", "The number of times the job should be executed."]
]
```ts highlights={highlights}
export default async function myCustomJob() {
console.log("I'll be executed three times only.")
}
export const config = {
name: "hello-world",
// execute every minute
schedule: "* * * * *",
numberOfExecutions: 3,
}
```
The above scheduled job has the `numberOfExecutions` configuration set to `3`.
So, it'll only execute 3 times, each every minute, then it won't be executed anymore.
<Note>
If you restart the Medusa application, the scheduled job will be executed again until reaching the number of executions specified.
</Note>
@@ -0,0 +1,52 @@
export const metadata = {
title: `${pageNumber} Access Workflow Errors`,
}
# {metadata.title}
In this chapter, youll learn how to access errors that occur during a workflows execution.
## How to Access Workflow Errors?
By default, when an error occurs in a workflow, it throws that error, and the execution stops.
You can configure the workflow to return the errors instead so that you can access and handle them differently.
For example:
export const highlights = [
["11", "errors", "`errors` is an array of errors that occur during the workflow's execution."],
["14", "throwOnError", "Specify that errors occuring during the workflow's execution should be returned, not thrown."],
]
```ts title="src/api/workflows/route.ts" highlights={highlights} collapsibleLines="1-6" expandButtonLabel="Show Imports"
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import myWorkflow from "../../../workflows/hello-world"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
const { result, errors } = await myWorkflow(req.scope)
.run({
// ...
throwOnError: false,
})
if (errors.length) {
return res.send({
errors: errors.map((error) => error.error),
})
}
res.send(result)
}
```
The object passed to the `run` method accepts a `throwOnError` property. When disabled, the errors are returned in the `errors` property of `run`'s output.
The value of `errors` is an array of error objects. Each object has an `error` property, whose value is the name or text of the thrown error.
@@ -0,0 +1,90 @@
export const metadata = {
title: `${pageNumber} Expose a Workflow Hook`,
}
# {metadata.title}
In this chapter, you'll learn how to expose a hook in your workflow.
## When to Expose a Hook
<Note title="Expose workflow hooks when" type="success">
Your workflow is reusable in other applications, and you allow performing an external action at some point in your workflow.
</Note>
<Note title="Don't expose workflow hooks if" type="error">
Your workflow isn't reusable by other applications. Use a step that performs what a hook handler would instead.
</Note>
---
## How to Expose a Hook in a Workflow?
To expose a hook in your workflow, use the `createHook` function imported from `@medusajs/framework/workflows-sdk`.
For example:
export const hookHighlights = [
["13", "createHook", "Add a hook to the workflow."],
["14", `"productCreated"`, "The hook's name."],
["15", "productId", "The data to pass to the hook handler."],
["19", "hooks", "Return the list of hooks in the workflow."]
]
```ts title="src/workflows/my-workflow/index.ts" highlights={hookHighlights}
import {
createStep,
createHook,
createWorkflow,
WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
import { createProductStep } from "./steps/create-product"
export const myWorkflow = createWorkflow(
"my-workflow",
function (input) {
const product = createProductStep(input)
const productCreatedHook = createHook(
"productCreated",
{ productId: product.id }
)
return new WorkflowResponse(product, {
hooks: [productCreatedHook],
})
}
)
```
The `createHook` function accepts two parameters:
1. The first is a string indicating the hook's name. You use this to consume the hook later.
2. The second is the input to pass to the hook handler.
The workflow must also pass an object having a `hooks` property as a second parameter to the `WorkflowResponse` constructor. Its value is an array of the workflow's hooks.
### How to Consume the Hook?
To consume the hook of the workflow, create the file `src/workflows/hooks/my-workflow.ts` with the following content:
export const handlerHighlights = [
["3", "productCreated", "Invoke the hook, passing it a step function as a parameter."],
]
```ts title="src/workflows/hooks/my-workflow.ts" highlights={handlerHighlights}
import { myWorkflow } from "../my-workflow"
myWorkflow.hooks.productCreated(
async ({ productId }, { container }) => {
// TODO perform an action
}
)
```
The hook is available on the workflow's `hooks` property using its name `productCreated`.
You invoke the hook, passing a step function (the hook handler) as a parameter.
@@ -0,0 +1,198 @@
export const metadata = {
title: `${pageNumber} Compensation Function`,
}
# {metadata.title}
In this chapter, you'll learn what a compensation function is and how to add it to a step.
## What is a Compensation Function
A compensation function rolls back or undoes changes made by a step when an error occurs in the workflow.
For example, if a step creates a record, the compensation function deletes the record when an error occurs later in the workflow.
By using compensation functions, you provide a mechanism that guarantees data consistency in your application and across systems.
---
## How to add a Compensation Function?
A compensation function is passed as a second parameter to the `createStep` function.
For example, create the file `src/workflows/hello-world.ts` with the following content:
```ts title="src/workflows/hello-world.ts" highlights={[["15"], ["16"], ["17"]]} collapsibleLines="1-5" expandButtonLabel="Show Imports"
import {
createStep,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
async () => {
const message = `Hello from step one!`
console.log(message)
return new StepResponse(message)
},
async () => {
console.log("Oops! Rolling back my changes...")
}
)
```
Each step can have a compensation function. The compensation function only runs if an error occurs throughout the workflow.
---
## Test the Compensation Function
Create a step in the same `src/workflows/hello-world.ts` file that throws an error:
```ts title="src/workflows/hello-world.ts"
const step2 = createStep(
"step-2",
async () => {
throw new Error("Throwing an error...")
}
)
```
Then, create a workflow that uses the steps:
```ts title="src/workflows/hello-world.ts" collapsibleLines="1-8" expandButtonLabel="Show Imports"
import {
createWorkflow,
WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
// other imports...
// steps...
const myWorkflow = createWorkflow(
"hello-world",
function (input) {
const str1 = step1()
step2()
return new WorkflowResponse({
message: str1,
})
})
export default myWorkflow
```
Finally, execute the workflow from an API route:
```ts title="src/api/workflow/route.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports"
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import myWorkflow from "../../../workflows/hello-world"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
const { result } = await myWorkflow(req.scope)
.run()
res.send(result)
}
```
Run the Medusa application and send a `GET` request to `/workflow`:
```bash
curl http://localhost:9000/workflow
```
In the console, you'll see:
- `Hello from step one!` logged in the terminal, indicating that the first step ran successfully.
- `Oops! Rolling back my changes...` logged in the terminal, indicating that the second step failed and the compensation function of the first step ran consequently.
---
## Pass Input to Compensation Function
If a step creates a record, the compensation function must receive the ID of the record to remove it.
To pass input to the compensation function, pass a second parameter in the `StepResponse` returned by the step.
For example:
export const inputHighlights = [
["11", "", "The data to pass as an input to the compensation function."],
["14", "{ message }", "The data received as an input from `StepResponse`'s second parameter."]
]
```ts highlights={inputHighlights}
import {
createStep,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
async () => {
return new StepResponse(
`Hello from step one!`,
{ message: "Oops! Rolling back my changes..." }
)
},
async ({ message }) => {
console.log(message)
}
)
```
In this example, the step passes an object as a second parameter to `StepResponse`.
The compensation function receives the object and uses its `message` property to log a message.
---
## Resolve Resources from the Medusa Container
The compensation function receives an object second parameter. The object has a `container` property that you use to resolve resources from the Medusa container.
For example:
export const containerHighlights = [
["15", "container", "Access the container in the second parameter object."],
["16", "resolve", "Use the container to resolve resources."]
]
```ts
import {
createStep,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
const step1 = createStep(
"step-1",
async () => {
return new StepResponse(
`Hello from step one!`,
{ message: "Oops! Rolling back my changes..." }
)
},
async ({ message }, { container }) => {
const logger = container.resolve(
ContainerRegistrationKeys.LOGGER
)
logger.info(message)
}
)
```
In this example, you use the `container` property in the second object parameter of the compensation function to resolve the logger.
You then use the logger to log a message.
@@ -0,0 +1,82 @@
export const metadata = {
title: `${pageNumber} Conditions in Workflows with When-Then`,
}
# {metadata.title}
In this chapter, you'll learn how to execute an action based on a condition in a workflow using the when-then utility.
## Why If-Conditions Aren't Allowed in Workflows?
Medusa creates an internal representation of the workflow definition you pass to `createWorkflow` to track and store its steps.
At that point, variables in the workflow don't have any values. They only do when you execute the workflow.
So, you can't use an if-condition that checks a variable's value, as the condition will be evaluated when Medusa creates the internal representation of the workflow, rather than during execution.
Instead, use the when-then utility.
---
## What is the When-Then Utility?
The when-then utility functions execute an action if a condition is satisfied.
The `when` function accepts as a parameter a function that returns a boolean value, and the `then` function is chained to `when`. `then` accepts as a parameter a function that's executed if `when`'s parameter function returns a `true` value.
For example:
export const highlights = [
["15", "input", "The data to pass as a parameter to the function in the second parameter"],
["17", "return", "The function must return a boolean value indicating whether\nthe callback function passed to `then` should be executed."],
["19", "() => {", "The function to execute if `when`'s second parameter returns a `true` value."]
]
```ts highlights={highlights}
import {
createWorkflow,
WorkflowResponse,
when,
} from "@medusajs/framework/workflows-sdk"
// step imports...
const workflow = createWorkflow(
"workflow",
function (input: {
is_active: boolean
}) {
const result = when(
input,
(input) => {
return input.is_active
}
).then(() => {
const stepResult = isActiveStep()
return stepResult
})
// executed without condition
const anotherStepResult = anotherStep(result)
return new WorkflowResponse(
anotherStepResult
)
}
)
```
In this code snippet, you execute the `isActiveStep` only if the `input.is_active`'s value is `true`.
### When Parameters
`when` utility is a function imported from `@medusajs/framework/workflows-sdk`. It accepts the following parameters:
1. The first parameter is either an object or the workflow's input. This data is passed as a parameter to the function in `when`'s second parameter.
2. The second parameter is a function that returns a boolean indicating whether to execute the action in `then`.
### Then Parameters
To specify the action to perform if the condition is satisfied, chain a `then` function to `when` and pass it a callback function.
The callback function is only executed if `when`'s second parameter function returns a `true` value.
@@ -0,0 +1,203 @@
export const metadata = {
title: `${pageNumber} Workflow Constraints`,
}
# {metadata.title}
This chapter lists constraints of defining a workflow or its steps.
## Workflow Constraints
### No Async Functions
The function passed to `createWorkflow` cant be an async function:
```ts highlights={[["4", "async", "Function can't be async."], ["11", "", "Correct way of defining the function."]]}
// Don't
const myWorkflow = createWorkflow(
"hello-world",
async function (input: WorkflowInput) {
// ...
})
// Do
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
// ...
})
```
### No Direct Variable Manipulation
You cant directly manipulate variables within the workflow's constructor function.
<Note>
Learn more about why you can't manipulate variables [in this chapter](../conditions/page.mdx#why-if-conditions-arent-allowed-in-workflows)
</Note>
Instead, use the `transform` utility function imported from `@medusajs/framework/workflows-sdk`:
export const highlights = [
["9", "", "Don't manipulate variables directly."],
["20", "transform", "Use the `transform` function to manipulate variables."]
]
```ts highlights={highlights}
// Don't
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
const str1 = step1(input)
const str2 = step2(input)
return new WorkflowResponse({
message: `${str1}${str2}`,
})
})
// Do
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
const str1 = step1(input)
const str2 = step2(input)
const result = transform(
{
str1,
str2,
},
(input) => ({
message: `${input.str1}${input.str2}`,
})
)
return new WorkflowResponse(result)
})
```
### No If Conditions
You can't use if-conditions in a workflow.
<Note>
Learn more about why you can't use if-conditions [in this chapter](../conditions/page.mdx#why-if-conditions-arent-allowed-in-workflows)
</Note>
Instead, use the when-then utility function imported from `@medusajs/framework/workflows-sdk`:
```ts
// Don't
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
if (input.is_active) {
// perform an action
}
})
// Do (explained in the next chapter)
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
when(input, (input) => {
return input.is_active
})
.then(() => {
// perform an action
})
})
```
### No Conditional Operators
You can't use conditional operators in a workflow, such as `??` or `||`.
<Note>
Learn more about why you can't use if-conditions [in this chapter](../conditions/page.mdx#why-if-conditions-arent-allowed-in-workflows)
</Note>
Instead, use `transform` to store the desired value in a variable.
For example:
```ts
// Don't
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
const message = input.message || "Hello"
})
// Do
// other imports...
import { transform } from "@medusajs/framework/workflows-sdk"
const myWorkflow = createWorkflow(
"hello-world",
function (input: WorkflowInput) {
const message = transform(
{
input
},
(data) => data.input.message || "hello"
)
})
```
---
## Step Constraints
### Returned Values
A step must only return serializable values, such as [primitive values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values) or an object.
Values of other types, such as Maps, aren't allowed.
```ts
// Don't
import {
createStep,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
(input, { container }) => {
const myMap = new Map()
// ...
return new StepResponse({
myMap,
})
}
)
// Do
import {
createStep,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
(input, { container }) => {
const myObj: Record<string, unknown> = {}
// ...
return new StepResponse({
myObj,
})
}
)
```
@@ -0,0 +1,155 @@
export const metadata = {
title: `${pageNumber} Execute Another Workflow`,
}
# {metadata.title}
In this chapter, you'll learn how to execute a workflow in another.
## Execute in a Workflow
To execute a workflow in another, use the `runAsStep` method that every workflow has.
For example:
export const workflowsHighlights = [
["11", "runAsStep", "Use the `runAsStep` method to run the workflow as a step."],
["12", "input", "Pass the input as you did in the `run` method before."]
]
```ts highlights={workflowsHighlights} collapsibleLines="1-7" expandMoreButton="Show Imports"
import {
createWorkflow,
} from "@medusajs/framework/workflows-sdk"
import {
createProductsWorkflow,
} from "@medusajs/medusa/core-flows"
const workflow = createWorkflow(
"hello-world",
async (input) => {
const products = createProductsWorkflow.runAsStep({
input: {
products: [
// ...
],
},
})
// ...
}
)
```
Instead of invoking the workflow, passing it the container, you use its `runAsStep` method and pass it an object as a parameter.
The object has an `input` property to pass input to the workflow.
---
## Preparing Input Data
If you need to perform some data manipulation to prepare the other workflow's input data, use the `transform` utility function imported from `@medusajs/framework/workflows-sdk`.
<Note>
Learn about the transform utility in [this chapter](../variable-manipulation/page.mdx).
</Note>
For example:
export const transformHighlights = [
["16", "transform", "Make changes to the input data before passing it to the workflow."],
["26", "createProductsData", "Pass the data prepared with the `transform` function to the workflow."]
]
```ts highlights={transformHighlights} collapsibleLines="1-12"
import {
createWorkflow,
transform,
} from "@medusajs/framework/workflows-sdk"
import {
createProductsWorkflow,
} from "@medusajs/medusa/core-flows"
type WorkflowInput = {
title: string
}
const workflow = createWorkflow(
"hello-product",
async (input: WorkflowInput) => {
const createProductsData = transform({
input,
}, (data) => [
{
title: `Hello ${data.input.title}`,
},
])
const products = createProductsWorkflow.runAsStep({
input: {
products: createProductsData,
},
})
// ...
}
)
```
In this example, you use the `transform` function to prepend `Hello` to the title of the product. Then, you pass the result as an input to the `createProductsWorkflow`.
---
## Run Workflow Conditionally
To run a workflow in another based on a condition, use the when-then utility functions imported from `@medusajs/framework/workflows-sdk`.
<Note>
Learn about the when-then utility in [this chapter](../conditions/page.mdx).
</Note>
For example:
export const whenHighlights = [
["20", "when", "If `should_create` passed in the input is enabled, then run the function passed to `then`."],
["22", "createProductsWorkflow", "Workflow only runs if `when`'s condition is `true`."]
]
```ts highlights={whenHighlights} collapsibleLines="1-16"
import {
createWorkflow,
when,
} from "@medusajs/framework/workflows-sdk"
import {
createProductsWorkflow,
} from "@medusajs/medusa/core-flows"
import {
CreateProductWorkflowInputDTO,
} from "@medusajs/framework/types"
type WorkflowInput = {
product?: CreateProductWorkflowInputDTO
should_create?: boolean
}
const workflow = createWorkflow(
"hello-product",
async (input: WorkflowInput) => {
const product = when(input, ({ should_create }) => should_create)
.then(() => {
return createProductsWorkflow.runAsStep({
input: {
products: [input.product],
},
})
})
}
)
```
In this example, you use the `when` utility to run the `createProductsWorkflow` only if `should_create` (passed in the `input`) is enabled.
@@ -0,0 +1,378 @@
import { TypeList } from "docs-ui"
export const metadata = {
title: `${pageNumber} Long-Running Workflows`,
}
# {metadata.title}
In this chapter, youll learn what a long-running workflow is and how to configure it.
## What is a Long-Running Workflow?
When you execute a workflow, you wait until the workflow finishes execution to receive the output.
A long-running workflow is a workflow that continues its execution in the background. You dont receive its output immediately. Instead, you subscribe to the workflow execution to listen to status changes and receive its result once the execution is finished.
### Why use Long-Running Workflows?
Long-running workflows are useful if:
- A task takes too long. For example, you're importing data from a CSV file.
- The workflow's steps wait for an external action to finish before resuming execution. For example, before you import the data from the CSV file, you wait until the import is confirmed by the user.
---
## Configure Long-Running Workflows
A workflow is considered long-running if at least one step has its `async` configuration set to `true` and doesn't return a step response.
For example, consider the following workflow and steps:
```ts title="src/workflows/hello-world.ts" highlights={[["15"]]} collapsibleLines="1-11" expandButtonLabel="Show More"
import {
createStep,
createWorkflow,
WorkflowResponse,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep("step-1", async () => {
return new StepResponse({})
})
const step2 = createStep(
{
name: "step-2",
async: true,
},
async () => {
console.log("Waiting to be successful...")
}
)
const step3 = createStep("step-3", async () => {
return new StepResponse("Finished three steps")
})
const myWorkflow = createWorkflow(
"hello-world",
function () {
step1()
step2()
const message = step3()
return new WorkflowResponse({
message,
})
})
export default myWorkflow
```
The second step has in its configuration object `async` set to `true` and it doesn't return a step response. This indicates that this step is an asynchronous step.
So, when you execute the `hello-world` workflow, it continues its execution in the background once it reaches the second step.
---
## Change Step Status
Once the workflow's execution reaches an async step, it'll wait in the background for the step to succeed or fail before it moves to the next step.
To fail or succeed a step, use the Workflow Engine Module's main service that is registered in the Medusa Container under the `Modules.WORKFLOW_ENGINE` (or `workflowsModuleService`) key.
### Retrieve Transaction ID
Before changing the status of a workflow execution's async step, you must have the execution's transaction ID.
When you execute the workflow, the object returned has a `transaction` property, which is an object that holds the details of the workflow execution's transaction. Use its `transactionId` to later change async steps' statuses:
```ts
const { transaction } = await myWorkflow(req.scope)
.run()
// use transaction.transactionId later
```
### Change Step Status to Successful
The Workflow Engine Module's main service has a `setStepSuccess` method to set a step's status to successful. If you use it on a workflow execution's async step, the workflow continues execution to the next step.
For example, consider the following step:
export const successStatusHighlights = [
["17", "transactionId", "Receive the workflow execution's transaction ID as an input to the step."],
["20", "resolve", "Resolve the workflow engine's main service."],
["24", "setStepSuccess", "Change the step's status to successful."],
["28", "stepId", "The ID of the step as passed to `createStep`'s first parameter when it was created."],
["29", "workflowId", "The ID of the workflow as passed to `createWorkflow`'s first parameter when it was created."],
["31", "stepResponse", "The response returned by the step, since an `async` step can't return a response in its definition."]
]
```ts highlights={successStatusHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports"
import {
Modules,
TransactionHandlerType,
} from "@medusajs/framework/utils"
import {
StepResponse,
createStep,
} from "@medusajs/framework/workflows-sdk"
type SetStepSuccessStepInput = {
transactionId: string
};
export const setStepSuccessStep = createStep(
"set-step-success-step",
async function (
{ transactionId }: SetStepSuccessStepInput,
{ container }
) {
const workflowEngineService = container.resolve(
Modules.WORKFLOW_ENGINE
)
await workflowEngineService.setStepSuccess({
idempotencyKey: {
action: TransactionHandlerType.INVOKE,
transactionId,
stepId: "step-2",
workflowId: "hello-world",
},
stepResponse: new StepResponse("Done!"),
options: {
container,
},
})
}
)
```
In this step (which you use in a workflow other than the long-running workflow), you resolve the Workflow Engine Module's main service and set `step-2` of the previous workflow as successful.
The `setStepSuccess` method of the workflow engine's main service accepts as a parameter an object having the following properties:
<TypeList
types={[
{
name: "idempotencyKey",
type: "`object`",
description: "The details of the workflow execution.",
optional: false,
children: [
{
name: "action",
type: "`invoke` | `compensate`",
description: "If the step's compensation function is running, use `compensate`. Otherwise, use `invoke`.",
optional: false
},
{
name: "transactionId",
type: "`string`",
description: "The ID of the workflow execution's transaction.",
optional: false
},
{
name: "stepId",
type: "`string`",
description: "The ID of the step to change its status. This is the first parameter passed to `createStep` when creating the step.",
optional: false
},
{
name: "workflowId",
type: "`string`",
description: "The ID of the workflow. This is the first parameter passed to `createWorkflow` when creating the workflow.",
optional: false
}
]
},
{
name: "stepResponse",
type: "`StepResponse`",
description: "Set the response of the step. This is similar to the response you return in a step's definition, but since the `async` step doesn't have a response, you set its response when changing its status.",
optional: false
},
{
name: "options",
type: "`Record<string, any>`",
description: "Options to pass to the step.",
optional: true,
children: [
{
name: "container",
type: "`MedusaContainer`",
description: "An instance of the Medusa Container",
optional: true
}
]
}
]}
/>
### Change Step Status to Failed
The Workflow Engine Module's main service also has a `setStepFailure` method that changes a step's status to failed. It accepts the same parameter as `setStepSuccess`.
After changing the async step's status to failed, the workflow execution fails and the compensation functions of previous steps are executed.
For example:
export const failureStatusHighlights = [
["17", "transactionId", "Receive the workflow execution's transaction ID as an input to the step."],
["20", "resolve", "Resolve the workflow engine's main service."],
["24", "setStepSuccess", "Change the step's status to successful."],
["28", "stepId", "The ID of the step as passed to `createStep`'s first parameter when it was created."],
["29", "workflowId", "The ID of the workflow as passed to `createWorkflow`'s first parameter when it was created."],
["31", "stepResponse", "The response returned by the step, since an `async` step can't return a response in its definition."]
]
```ts highlights={failureStatusHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports"
import {
Modules,
TransactionHandlerType,
} from "@medusajs/framework/utils"
import {
StepResponse,
createStep,
} from "@medusajs/framework/workflows-sdk"
type SetStepFailureStepInput = {
transactionId: string
};
export const setStepFailureStep = createStep(
"set-step-success-step",
async function (
{ transactionId }: SetStepFailureStepInput,
{ container }
) {
const workflowEngineService = container.resolve(
Modules.WORKFLOW_ENGINE
)
await workflowEngineService.setStepFailure({
idempotencyKey: {
action: TransactionHandlerType.INVOKE,
transactionId,
stepId: "step-2",
workflowId: "hello-world",
},
stepResponse: new StepResponse("Failed!"),
options: {
container,
},
})
}
)
```
You use this step in another workflow that changes the status of an async step in a long-running workflow's execution to failed.
---
## Access Long-Running Workflow Status and Result
To access the status and result of a long-running workflow execution, use the `subscribe` and `unsubscribe` methods of the Workflow Engine Module's main service.
For example:
export const highlights = [
["18", "resolve", "Resolve the workflow engine from the Medusa container."],
["30", "subscribe", "Subscribe to status changes of the workflow execution."],
]
```ts title="src/api/workflows/route.ts" highlights={highlights} collapsibleLines="1-11" expandButtonLabel="Show Imports"
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import myWorkflow from "../../../workflows/hello-world"
import {
IWorkflowEngineService,
} from "@medusajs/framework/types"
import { Modules } from "@medusajs/framework/utils"
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const { transaction, result } = await myWorkflow(req.scope).run()
const workflowEngineService = req.scope.resolve<
IWorkflowEngineService
>(
Modules.WORKFLOW_ENGINE
)
const subscriptionOptions = {
workflowId: "hello-world",
transactionId: transaction.transactionId,
subscriberId: "hello-world-subscriber",
}
await workflowEngineService.subscribe({
...subscriptionOptions,
subscriber: async (data) => {
if (data.eventType === "onFinish") {
console.log("Finished execution", data.result)
// unsubscribe
await workflowEngineService.unsubscribe({
...subscriptionOptions,
subscriberOrId: subscriptionOptions.subscriberId,
})
} else if (data.eventType === "onStepFailure") {
console.log("Workflow failed", data.step)
}
},
})
res.send(result)
}
```
In the above example, you execute the long-running workflow `hello-world` and resolve the Workflow Engine Module's main service from the Medusa container.
### subscribe Method
The main service's `subscribe` method allows you to listen to changes in the workflow executions status. It accepts an object having three properties:
<TypeList
types={[
{
name: "workflowId",
type: "`string`",
description: "The name of the workflow.",
},
{
name: "transactionId",
type: "`string`",
description:
"The ID of the workflow exection's transaction. The transaction's details are returned in the response of the workflow execution.",
},
{
name: "subscriberId",
type: "`string`",
description:
"The ID of the subscriber.",
},
{
name: "subscriber",
type: "`(data: { eventType: string, result?: any }) => Promise<void>`",
description:
"The function executed when the workflow execution's status changes. The function receives a data object. It has an `eventType` property, which you use to check the status of the workflow execution.",
},
]}
sectionTitle="Access Long-Running Workflow Status and Result"
/>
If the value of `eventType` in the `subscriber` function's first parameter is `onFinish`, the workflow finished executing. The first parameter then also has a `result` property holding the workflow's output.
### unsubscribe Method
You can unsubscribe from the workflow using the workflow engine's `unsubscribe` method, which requires the same object parameter as the `subscribe` method.
However, instead of the `subscriber` property, it requires a `subscriberOrId` property whose value is the same `subscriberId` passed to the `subscribe` method.
---
## Example: Restaurant-Delivery Recipe
To find a full example of a long-running workflow, refer to the [restaurant-delivery recipe](!resources!/recipes/marketplace/examples/restaurant-delivery).
In the recipe, you use a long-running workflow that moves an order from placed to completed. The workflow waits for the restaurant to accept the order, the driver to pick up the order, and other external actions.
@@ -0,0 +1,14 @@
export const metadata = {
title: `${pageNumber} Workflows Advanced Development`,
}
# {metadata.title}
In the next chapters, you'll learn about workflows in-depth and how to use them in your custom development.
By the end of these chapters, you'll learn about:
- Constructing a workflow and its constraints.
- Using a compensation function to undo a step's action when errors occur.
- Hooks and how to consume and expose them.
- Configurations to retry workflows or run them in the background.
@@ -0,0 +1,61 @@
export const metadata = {
title: `${pageNumber} Run Workflow Steps in Parallel`,
}
# {metadata.title}
In this chapter, youll learn how to run workflow steps in parallel.
## parallelize Utility Function
If your workflow has steps that dont rely on one anothers results, run them in parallel using the `parallelize` utility function imported from the `@medusajs/framework/workflows-sdk`.
The workflow waits until all steps passed to the `parallelize` function finish executing before continuing to the next step.
For example:
export const highlights = [
["22", "[prices, productSalesChannel]", "The result of the steps. `prices` is the result of `createPricesStep`, and `productSalesChannel` is the result of `attachProductToSalesChannelStep`."],
["22", "parallelize", "Run the steps passed as parameters in parallel."],
]
```ts highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
import {
createWorkflow,
WorkflowResponse,
parallelize,
} from "@medusajs/framework/workflows-sdk"
import {
createProductStep,
getProductStep,
createPricesStep,
attachProductToSalesChannelStep,
} from "./steps"
interface WorkflowInput {
title: string
}
const myWorkflow = createWorkflow(
"my-workflow",
(input: WorkflowInput) => {
const product = createProductStep(input)
const [prices, productSalesChannel] = parallelize(
createPricesStep(product),
attachProductToSalesChannelStep(product)
)
const id = product.id
const refetchedProduct = getProductStep(product.id)
return new WorkflowResponse(refetchedProduct)
}
)
```
The `parallelize` function accepts the steps to run in parallel as a parameter.
It returns an array of the steps' results in the same order they're passed to the `parallelize` function.
So, `prices` is the result of `createPricesStep`, and `productSalesChannel` is the result of `attachProductToSalesChannelStep`.
@@ -0,0 +1,84 @@
export const metadata = {
title: `${pageNumber} Retry Failed Steps`,
}
# {metadata.title}
In this chapter, youll learn how to configure steps to allow retrial on failure.
## Configure a Steps Retrial
By default, when an error occurs in a step, the step and the workflow fail, and the execution stops.
You can configure the step to retry on failure. The `createStep` function can accept a configuration object instead of the steps name as a first parameter.
For example:
```ts title="src/workflows/hello-world.ts" highlights={[["10"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
import {
createStep,
createWorkflow,
WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
{
name: "step-1",
maxRetries: 2,
},
async () => {
console.log("Executing step 1")
throw new Error("Oops! Something happened.")
}
)
const myWorkflow = createWorkflow(
"hello-world",
function () {
const str1 = step1()
return new WorkflowResponse({
message: str1,
})
})
export default myWorkflow
```
The steps configuration object accepts a `maxRetries` property, which is a number indicating the number of times a step can be retried when it fails.
When you execute the above workflow, youll see the following result in the terminal:
```bash
Executing step 1
Executing step 1
Executing step 1
error: Oops! Something happened.
Error: Oops! Something happened.
```
The first line indicates the first time the step was executed, and the next two lines indicate the times the step was retried. After that, the step and workflow fail.
---
## Step Retry Intervals
By default, a step is retried immediately after it fails.
To specify a wait time before a step is retried, pass a `retryInterval` property to the step's configuration object. Its value is a number of seconds to wait before retrying the step.
For example:
```ts title="src/workflows/hello-world.ts" highlights={[["5"]]}
const step1 = createStep(
{
name: "step-1",
maxRetries: 2,
retryInterval: 2, // 2 seconds
},
async () => {
// ...
}
)
```
@@ -0,0 +1,116 @@
export const metadata = {
title: `${pageNumber} Variable Manipulation in Workflows with transform`,
}
# {metadata.title}
In this chapter, you'll learn how to manipulate variables in a workflow using the transform utility.
## Why Variable Manipulation isn't Allowed in Worflows?
Medusa creates an internal representation of the workflow definition you pass to `createWorkflow` to track and store its steps.
At that point, variables in the workflow don't have any values. They only do when you execute the workflow.
So, you can only pass variables as parameters to steps. But, in a workflow, you can't change a variable's value or, if the variable is an array, loop over its items.
Instead, use the transform utility.
---
## What is the transform Utility?
The `transform` utility function creates a new variable as the result of manipulating other variables.
For example, consider you have two strings as the output of two steps:
```ts
const str1 = step1()
const str2 = step2()
```
To concatinate the strings, you create a new variable `str3` using the `transform` function:
export const highlights = [
["14", "str3", "Holds the result returned by `transform`'s second parameter function."],
["15", "", "Specify the data to pass as a parameter to the function in the second parameter."],
["16", "data", "The data passed in the first parameter of `transform`."],
["16", "`${data.str1}${data.str2}`", "Return the concatenated strings."]
]
```ts highlights={highlights}
import {
createWorkflow,
WorkflowResponse,
transform,
} from "@medusajs/framework/workflows-sdk"
// step imports...
const myWorkflow = createWorkflow(
"hello-world",
function (input) {
const str1 = step1(input)
const str2 = step2(input)
const str3 = transform(
{ str1, str2 },
(data) => `${data.str1}${data.str2}`
)
return new WorkflowResponse(str3)
}
)
```
The `transform` utility function is imported from `@medusajs/framework/workflows-sdk`. It accepts two parameters:
1. The first parameter is an object of variables to manipulate. The object is passed as a parameter to `transform`'s second parameter function.
2. The second parameter is the function performing the variable manipulation.
The value returned by the second parameter function is returned by `transform`. So, the `str3` variable holds the concatenated string.
You can use the returned value in the rest of the workflow, either to pass it as an input to other steps or to return it in the workflow's response.
---
## Example: Looping Over Array
Use `transform` to loop over arrays to create another variable from the array's items.
For example:
```ts collapsibleLines="1-7" expandButtonLabel="Show Imports"
import {
createWorkflow,
WorkflowResponse,
transform,
} from "@medusajs/framework/workflows-sdk"
// step imports...
type WorkflowInput = {
items: {
id: string
name: string
}[]
}
const myWorkflow = createWorkflow(
"hello-world",
function ({ items }: WorkflowInput) {
const ids = transform(
{ items },
(data) => data.items.map((item) => item.id)
)
doSomethingStep(ids)
// ...
}
)
```
This workflow receives an `items` array in its input.
You use the `transform` utility to create an `ids` variable, which is an array of strings holding the `id` of each item in the `items` array.
You then pass the `ids` variable as a parameter to the `doSomethingStep`.
@@ -0,0 +1,150 @@
export const metadata = {
title: `${pageNumber} Workflow Hooks`,
}
# {metadata.title}
In this chapter, you'll learn what a workflow hook is and how to consume them.
## What is a Workflow Hook?
A workflow hook is a point in a workflow where you can inject custom functionality as a step function, called a hook handler.
Medusa exposes hooks in many of its workflows that are used in its API routes. You can consume those hooks to add your custom logic.
<Note title="Tip">
Refer to the [Workflows Reference](!resources!/medusa-workflows-reference) to view all workflows and their hooks.
</Note>
<Note title="Consume workflow hooks when" type="success">
You want to perform a custom action during a workflow's execution, such as when a product is created.
</Note>
---
## How to Consume a Hook?
A workflow has a special `hooks` property which is an object that holds its hooks.
So, in a TypeScript or JavaScript file created under the `src/workflows/hooks` directory:
- Import the workflow.
- Access its hook using the `hooks` property.
- Pass the hook a step function as a parameter to consume it.
For example, to consume the `productsCreated` hook of Medusa's `createProductsWorkflow`, create the file `src/workflows/hooks/product-created.ts` with the following content:
export const handlerHighlights = [
["3", "productsCreated", "Invoke the hook, passing it a step function as a parameter."],
]
```ts title="src/workflows/hooks/product-created.ts" highlights={handlerHighlights}
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
createProductsWorkflow.hooks.productsCreated(
async ({ products }, { container }) => {
// TODO perform an action
}
)
```
The `productsCreated` hook is available on the workflow's `hooks` property by its name.
You invoke the hook, passing a step function (the hook handler) as a parameter.
Now, when a product is created using the [Create Product API route](!api!/admin#products_postproducts), your hook handler is executed after the product is created.
<Note>
A hook can have only one handler.
</Note>
<Note title="Tip">
Refer to the [createProductsWorkflow reference](!resources!/references/medusa-workflows/createProductsWorkflow) to see at which point the hook handler is executed.
</Note>
### Hook Handler Parameter
Since a hook handler is essentially a step function, it receives the hook's input as a first parameter, and an object holding a `container` property as a second parameter.
Each hook has different input. For example, the `productsCreated` hook receives an object having a `products` property holding the created product.
### Hook Handler Compensation
Since the hook handler is a step function, you can set its compensation function as a second parameter of the hook.
For example:
```ts title="src/workflows/hooks/product-created.ts"
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
createProductsWorkflow.productCreated(
async ({ productId }, { container }) => {
// TODO perform an action
return new StepResponse(undefined, { ids })
},
async ({ ids }, { container }) => {
// undo the performed action
}
)
```
The compensation function is executed if an error occurs in the workflow to undo the actions performed by the hook handler.
The compensation function receives as an input the second parameter passed to the `StepResponse` returned by the step function.
It also accepts as a second parameter an object holding a `container` property to resolve resources from the Medusa container.
### Additional Data Property
Medusa's workflows pass in the hook's input an `additional_data` property:
```ts title="src/workflows/hooks/product-created.ts" highlights={[["4", "additional_data"]]}
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
createProductsWorkflow.hooks.productsCreated(
async ({ products, additional_data }, { container }) => {
// TODO perform an action
}
)
```
This property is an object that holds additional data passed to the workflow through the request sent to the API route using the workflow.
<Note>
Learn how to pass `additional_data` in requests to API routes in [this chapter](../../api-routes/additional-data/page.mdx).
</Note>
### Pass Additional Data to Workflow
You can also pass that additional data when executing the workflow. Pass it as a parameter to the `.run` method of the workflow:
```ts title="src/workflows/hooks/product-created.ts" highlights={[["10", "additional_data"]]}
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
export async function POST(req: MedusaRequest, res: MedusaResponse) {
await createProductsWorkflow(req.scope).run({
input: {
products: [
// ...
],
additional_data: {
custom_field: "test",
},
},
})
}
```
Your hook handler then receives that passed data in the `additional_data` object.
@@ -0,0 +1,100 @@
export const metadata = {
title: `${pageNumber} Workflow Timeout`,
}
# {metadata.title}
In this chapter, youll learn how to set a timeout for workflows and steps.
## What is a Workflow Timeout?
By default, a workflow doesnt have a timeout. It continues execution until its finished or an error occurs.
You can configure a workflows timeout to indicate how long the workflow can execute. If a workflow's execution time passes the configured timeout, it is failed and an error is thrown.
### Timeout Doesn't Stop Step Execution
Configuring a timeout doesn't stop the execution of a step in progress. The timeout only affects the status of the workflow and its result.
---
## Configure Workflow Timeout
The `createWorkflow` function can accept a configuration object instead of the workflows name.
In the configuration object, you pass a `timeout` property, whose value is a number indicating the timeout in seconds.
For example:
```ts title="src/workflows/hello-world.ts" highlights={[["16"]]} collapsibleLines="1-13" expandButtonLabel="Show More"
import {
createStep,
createWorkflow,
WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep(
"step-1",
async () => {
// ...
}
)
const myWorkflow = createWorkflow({
name: "hello-world",
timeout: 2, // 2 seconds
}, function () {
const str1 = step1()
return new WorkflowResponse({
message: str1,
})
})
export default myWorkflow
```
This workflow's executions fail if they run longer than two seconds.
<Note title="Tip">
A workflows timeout error is returned in the `errors` property of the workflows execution, as explained in [this chapter](../access-workflow-errors/page.mdx). The errors name is `TransactionTimeoutError`.
</Note>
---
## Configure Step Timeout
Alternatively, you can configure the timeout for a step rather than the entire workflow.
<Note>
As mentioned in the previous section, the timeout doesn't stop the execution of the step. It only affects the step's status and output.
</Note>
The steps configuration object accepts a `timeout` property, whose value is a number indicating the timeout in seconds.
For example:
```tsx
const step1 = createStep(
{
name: "step-1",
timeout: 2, // 2 seconds
},
async () => {
// ...
}
)
```
This step's executions fail if they run longer than two seconds.
<Note title="Tip">
A steps timeout error is returned in the `errors` property of the workflows execution, as explained in [this chapter](../access-workflow-errors/page.mdx). The errors name is `TransactionStepTimeoutError`.
</Note>