docs: fixes to customization docs (#9236)

Closes #9225, #9224, #9226, #9227

Closes DOCS-948, DOCS-947, DOCS-945, DOCS-946
This commit is contained in:
Shahed Nasser
2024-09-26 13:00:37 +00:00
committed by GitHub
parent 474ba92d48
commit ea2cc974cc
10 changed files with 53 additions and 45 deletions
@@ -73,10 +73,10 @@ export default defineMiddlewares({
method: "POST", method: "POST",
matcher: "/admin/products", matcher: "/admin/products",
additionalDataValidator: { additionalDataValidator: {
brand: z.string().optional() brand: z.string().optional(),
} },
} },
] ],
}) })
``` ```
@@ -154,14 +154,14 @@ createProductsWorkflow.hooks.productsCreated(
...product, ...product,
metadata: { metadata: {
...product.metadata, ...product.metadata,
brand: additional_data.brand brand: additional_data.brand,
} },
})) }))
) )
return new StepResponse(products, { return new StepResponse(products, {
products, products,
additional_data additional_data,
}) })
} }
) )
@@ -160,7 +160,7 @@ export const updateAssociationHighlights = [
const product = await helloModuleService.retrieveProduct( const product = await helloModuleService.retrieveProduct(
"123", "123",
{ {
relations: ["orders"] relations: ["orders"],
} }
) )
@@ -169,7 +169,7 @@ const updatedProduct = await helloModuleService.updateProducts({
// other properties... // other properties...
orders: [ orders: [
...product.orders.map((order) => order.id), ...product.orders.map((order) => order.id),
"321" "321",
], ],
}) })
``` ```
@@ -151,14 +151,14 @@ import { model } from "@medusajs/utils"
const Order = model.define("order", { const Order = model.define("order", {
id: model.id().primaryKey(), id: model.id().primaryKey(),
products: model.manyToMany(() => Product, { products: model.manyToMany(() => Product, {
mappedBy: "orders" mappedBy: "orders",
}), }),
}) })
const Product = model.define("product", { const Product = model.define("product", {
id: model.id().primaryKey(), id: model.id().primaryKey(),
orders: model.manyToMany(() => Order, { orders: model.manyToMany(() => Order, {
mappedBy: "products" mappedBy: "products",
}), }),
}) })
``` ```
@@ -142,7 +142,7 @@ const step1 = createStep(
async () => { async () => {
return new StepResponse( return new StepResponse(
`Hello from step one!`, `Hello from step one!`,
{ message: "Oops! Rolling back my changes..."} { message: "Oops! Rolling back my changes..." }
) )
}, },
async ({ message }) => { async ({ message }) => {
@@ -180,7 +180,7 @@ const step1 = createStep(
async () => { async () => {
return new StepResponse( return new StepResponse(
`Hello from step one!`, `Hello from step one!`,
{ message: "Oops! Rolling back my changes..."} { message: "Oops! Rolling back my changes..." }
) )
}, },
async ({ message }, { container }) => { async ({ message }, { container }) => {
@@ -114,11 +114,11 @@ export const successStatusHighlights = [
import { import {
Modules, Modules,
TransactionHandlerType, TransactionHandlerType,
} from "@medusajs/utils"; } from "@medusajs/utils"
import { import {
StepResponse, StepResponse,
createStep createStep,
} from "@medusajs/workflows-sdk"; } from "@medusajs/workflows-sdk"
type SetStepSuccessStepInput = { type SetStepSuccessStepInput = {
transactionId: string transactionId: string
@@ -132,7 +132,7 @@ export const setStepSuccessStep = createStep(
) { ) {
const workflowEngineService = container.resolve( const workflowEngineService = container.resolve(
Modules.WORKFLOW_ENGINE Modules.WORKFLOW_ENGINE
); )
await workflowEngineService.setStepSuccess({ await workflowEngineService.setStepSuccess({
idempotencyKey: { idempotencyKey: {
@@ -145,9 +145,9 @@ export const setStepSuccessStep = createStep(
options: { options: {
container, 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. 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.
@@ -232,11 +232,11 @@ export const failureStatusHighlights = [
import { import {
Modules, Modules,
TransactionHandlerType, TransactionHandlerType,
} from "@medusajs/utils"; } from "@medusajs/utils"
import { import {
StepResponse, StepResponse,
createStep createStep,
} from "@medusajs/workflows-sdk"; } from "@medusajs/workflows-sdk"
type SetStepFailureStepInput = { type SetStepFailureStepInput = {
transactionId: string transactionId: string
@@ -250,7 +250,7 @@ export const setStepFailureStep = createStep(
) { ) {
const workflowEngineService = container.resolve( const workflowEngineService = container.resolve(
Modules.WORKFLOW_ENGINE Modules.WORKFLOW_ENGINE
); )
await workflowEngineService.setStepFailure({ await workflowEngineService.setStepFailure({
idempotencyKey: { idempotencyKey: {
@@ -263,9 +263,9 @@ export const setStepFailureStep = createStep(
options: { options: {
container, 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. You use this step in another workflow that changes the status of an async step in a long-running workflow's execution to failed.
@@ -77,17 +77,18 @@ The [createProductsWorkflow](!resources!/references/medusa-workflows/createProdu
So, to consume the `productsCreated` hook, create the file `src/workflows/hooks/created-product.ts` with the following content: So, to consume the `productsCreated` hook, create the file `src/workflows/hooks/created-product.ts` with the following content:
export const hookHighlights = [ export const hookHighlights = [
["6", "productsCreated", "Access the hook in the `hooks` property."], ["7", "productsCreated", "Access the hook in the `hooks` property."],
["8", "", "Only proceed if the brand ID is passed in the additional data."], ["9", "", "Only proceed if the brand ID is passed in the additional data."],
["17", "retrieveBrand", "Try to retrieve the brand to ensure it exists."], ["18", "retrieveBrand", "Try to retrieve the brand to ensure it exists."],
["21", "links", "Define an array to store the links in."], ["27", "links", "Define an array to store the links in."],
["25", "push", "Add a link to be created."], ["31", "push", "Add a link to be created."],
["35", "create", "Create the links."] ["41", "create", "Create the links."]
] ]
```ts title="src/workflows/hooks/created-product.ts" highlights={hookHighlights} ```ts title="src/workflows/hooks/created-product.ts" highlights={hookHighlights}
import { createProductsWorkflow } from "@medusajs/core-flows" import { createProductsWorkflow } from "@medusajs/core-flows"
import { Modules } from "@medusajs/utils" import { StepResponse } from "@medusajs/workflows-sdk"
import { Modules, ContainerRegistrationKeys } from "@medusajs/utils"
import { BRAND_MODULE } from "../../modules/brand" import { BRAND_MODULE } from "../../modules/brand"
import BrandModuleService from "../../modules/brand/service" import BrandModuleService from "../../modules/brand/service"
@@ -104,7 +105,12 @@ createProductsWorkflow.hooks.productsCreated(
// if the brand doesn't exist, an error is thrown. // if the brand doesn't exist, an error is thrown.
await brandModuleService.retrieveBrand(additional_data.brand_id as string) await brandModuleService.retrieveBrand(additional_data.brand_id as string)
const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK) const remoteLink = container.resolve(
ContainerRegistrationKeys.REMOTE_LINK
)
const logger = container.resolve(
ContainerRegistrationKeys.LOGGER
)
const links = [] const links = []
@@ -122,8 +128,10 @@ createProductsWorkflow.hooks.productsCreated(
await remoteLink.create(links) await remoteLink.create(links)
logger.info("Linked brand to products")
return new StepResponse(links, links) return new StepResponse(links, links)
}) })
) )
``` ```
@@ -139,8 +147,8 @@ Add the following compensation function as a second parameter:
```ts title="src/workflows/hooks/created-product.ts" ```ts title="src/workflows/hooks/created-product.ts"
createProductsWorkflow.hooks.productsCreated( createProductsWorkflow.hooks.productsCreated(
// ... // ...
(async ({ links }, { container }) => { (async (links, { container }) => {
if (!links.length) { if (!links.length) {
return return
} }
@@ -149,7 +157,7 @@ createProductsWorkflow.hooks.productsCreated(
ContainerRegistrationKeys.REMOTE_LINK ContainerRegistrationKeys.REMOTE_LINK
) )
await remoteLink.dimiss(links) await remoteLink.dismiss(links)
}) })
) )
``` ```
@@ -112,7 +112,7 @@ Make sure to replace the email and password with your user's credentials.
Then, send a `GET` request to `/admin/products/:id/brand`: Then, send a `GET` request to `/admin/products/:id/brand`:
```bash ```bash
curl 'http://localhost:9000/admin/product/prod_123/brand' \ curl 'http://localhost:9000/admin/products/prod_123/brand' \
-H 'Authorization: Bearer {token}' -H 'Authorization: Bearer {token}'
``` ```
@@ -176,7 +176,7 @@ import { syncBrandToSystemWorkflow } from "../workflows/sync-brand-to-system"
export default async function brandCreatedHandler({ export default async function brandCreatedHandler({
event: { data }, event: { data },
container, container,
}: SubscriberArgs<Record<string, string>>) { }: SubscriberArgs<{ id: string }>) {
await syncBrandToSystemWorkflow(container).run({ await syncBrandToSystemWorkflow(container).run({
input: data, input: data,
}) })
@@ -53,7 +53,7 @@ export class BrandClient {
const moduleDef = configModule.modules[BRAND_MODULE] const moduleDef = configModule.modules[BRAND_MODULE]
if (typeof moduleDef !== "boolean") { if (typeof moduleDef !== "boolean") {
this.options_ = moduleDef.options this.options_ = moduleDef.options as BrandClientOptions
} }
} }
} }
@@ -101,7 +101,7 @@ export class BrandClient {
}`) }`)
} }
async createBrand(brand: Record<string, string>) { async createBrand(brand: Record<string, any>) {
await this.sendRequest("/brands", "POST", brand) await this.sendRequest("/brands", "POST", brand)
} }
@@ -51,22 +51,22 @@ Next, create the file `instrumentation.js` with the following content:
```js title="instrumentation.js" ```js title="instrumentation.js"
const { registerOtel } = require("@medusajs/medusa") const { registerOtel } = require("@medusajs/medusa")
// If using an exporter other than Zipkin, require it here. // If using an exporter other than Zipkin, require it here.
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin') const { ZipkinExporter } = require("@opentelemetry/exporter-zipkin")
// If using an exporter other than Zipkin, initialize it here. // If using an exporter other than Zipkin, initialize it here.
const exporter = new ZipkinExporter({ const exporter = new ZipkinExporter({
serviceName: 'my-medusa-project', serviceName: "my-medusa-project",
}) })
export function register() { export function register() {
registerOtel({ registerOtel({
serviceName: 'medusajs', serviceName: "medusajs",
// pass exporter // pass exporter
exporter, exporter,
instrument: { instrument: {
http: true, http: true,
workflows: true, workflows: true,
remoteQuery: true remoteQuery: true,
}, },
}) })
} }