diff --git a/www/apps/book/app/advanced-development/workflows/workflow-hooks/page.mdx b/www/apps/book/app/advanced-development/workflows/workflow-hooks/page.mdx new file mode 100644 index 0000000000000..c8ecb97c848ef --- /dev/null +++ b/www/apps/book/app/advanced-development/workflows/workflow-hooks/page.mdx @@ -0,0 +1,78 @@ +export const metadata = { + title: `${pageNumber} Workflow Hooks`, +} + +# {metadata.title} + +In this chapter, you'll learn what a workflow hook is, and an example of how to consume a workflow hook defined in Medusa. + +## 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. + +Hook handlers receive input from the workflow to perform custom actions during the workflow's execution. + + + +- Your workflow is reusable in other applications, and you allow performing an external action at some point in your workflow. + + + + + +- Your workflow isn't reusable by other applications. Use a step that performs what a hook handler would instead. + + + +--- + +## How to Consume a Hook? + +You consume a hook by registering a hook handler on the workflow. A hook handler is registered in a TypeScript or JavaScript file created in the `src/workflows/hooks` directory. + +You'll find a workflow's exposed hooks in its `hooks` property. + +For example, to consume the `productsCreated` hook of the `createProductsWorkflow`, which Medusa uses when a product is created using the admin API routes, 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 + } +) +``` + + + +A hook can have only one handler. + + + +The hook is available on the workflow's `hooks` property using its name `productCreated`. You invoke the hook, passing the handler as a parameter, which is a step function. + +Similar to a step, the handler receives the hook's input as a first parameter, and the container in the object as a second parameter. + +### Hook Handler Compensation + +You can also pass a compensation function as a second parameter: + +```ts +import { myWorkflow } from "../my-workflow" + +myWorkflow.hooks.productCreated( + async ({ productId }, { container }) => { + // TODO perform an action + }, + async () => { + // 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.