1 import { CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `Medusa Examples`,
5 }
6
7 # {metadata.title}
8
9 This documentation page has examples of customizations useful for your custom development in the Medusa application.
10
11 Each section links to the associated documentation page to learn more about it.
12
13 ## API Routes
14
15 An API route is a REST API endpoint that exposes commerce features to external applications, such as storefronts, the admin dashboard, or third-party systems.
16
17 ### Create API Route
18
19 Create the file `src/api/hello-world/route.ts` with the following content:
20
21 ```ts title="src/api/hello-world/route.ts"
22 import type {
23 MedusaRequest,
24 MedusaResponse,
25 } from "@medusajs/framework/http"
26
27 export const GET = (
28 req: MedusaRequest,
29 res: MedusaResponse
30 ) => {
31 res.json({
32 message: "[GET] Hello world!",
33 })
34 }
35 ```
36
37 This creates a `GET` API route at `/hello-world`.
38
39 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes).
40
41 ### Resolve Resources in API Route
42
43 To resolve resources from the Medusa container in an API route:
44
45 ```ts highlights={[["8", "resolve", "Resolve the Product Module's\nmain service from the Medusa container."]]}
46 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
47 import { Modules } from "@medusajs/framework/utils"
48
49 export const GET = async (
50 req: MedusaRequest,
51 res: MedusaResponse
52 ) => {
53 const productModuleService = req.scope.resolve(
54 Modules.PRODUCT
55 )
56
57 const [, count] = await productModuleService
58 .listAndCountProducts()
59
60 res.json({
61 count,
62 })
63 }
64 ```
65
66 This resolves the Product Module's main service.
67
68 Learn more in [this documentation](!docs!/learn/fundamentals/medusa-container).
69
70 ### Use Path Parameters
71
72 API routes can accept path parameters.
73
74 To do that, create the file `src/api/hello-world/[id]/route.ts` with the following content:
75
76 export const singlePathHighlights = [
77 ["11", "req.params.id", "Access the path parameter `id`"]
78 ]
79
80 ```ts title="src/api/hello-world/[id]/route.ts" highlights={singlePathHighlights}
81 import type {
82 MedusaRequest,
83 MedusaResponse,
84 } from "@medusajs/framework/http"
85
86 export const GET = async (
87 req: MedusaRequest,
88 res: MedusaResponse
89 ) => {
90 res.json({
91 message: `[GET] Hello ${req.params.id}!`,
92 })
93 }
94 ```
95
96 Learn more about path parameters in [this documentation](!docs!/learn/fundamentals/api-routes/parameters#path-parameters).
97
98 ### Use Query Parameters
99
100 API routes can accept query parameters:
101
102 export const queryHighlights = [
103 ["11", "req.query.name", "Access the query parameter `name`"],
104 ]
105
106 ```ts highlights={queryHighlights}
107 import type {
108 MedusaRequest,
109 MedusaResponse,
110 } from "@medusajs/framework/http"
111
112 export const GET = async (
113 req: MedusaRequest,
114 res: MedusaResponse
115 ) => {
116 res.json({
117 message: `Hello ${req.query.name}`,
118 })
119 }
120 ```
121
122 Learn more about query parameters in [this documentation](!docs!/learn/fundamentals/api-routes/parameters#query-parameters).
123
124 ### Use Body Parameters
125
126 API routes can accept request body parameters:
127
128 export const bodyHighlights = [
129 ["11", "HelloWorldReq", "Specify the type of the request body parameters."],
130 ["15", "req.body.name", "Access the request body parameter `name`"],
131 ]
132
133 ```ts highlights={bodyHighlights}
134 import type {
135 MedusaRequest,
136 MedusaResponse,
137 } from "@medusajs/framework/http"
138
139 type HelloWorldReq = {
140 name: string
141 }
142
143 export const POST = async (
144 req: MedusaRequest<HelloWorldReq>,
145 res: MedusaResponse
146 ) => {
147 res.json({
148 message: `[POST] Hello ${req.body.name}!`,
149 })
150 }
151 ```
152
153 Learn more about request body parameters in [this documentation](!docs!/learn/fundamentals/api-routes/parameters#request-body-parameters).
154
155 ### Set Response Code
156
157 You can change the response code of an API route:
158
159 ```ts highlights={[["7", "status", "Change the response's status."]]}
160 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
161
162 export const GET = async (
163 req: MedusaRequest,
164 res: MedusaResponse
165 ) => {
166 res.status(200).json({
167 message: "Hello, World!",
168 })
169 }
170 ```
171
172 Learn more about setting the response code in [this documentation](!docs!/learn/fundamentals/api-routes/responses#set-response-status-code).
173
174 ### Execute a Workflow in an API Route
175
176 To execute a workflow in an API route:
177
178 ```ts
179 import type {
180 MedusaRequest,
181 MedusaResponse,
182 } from "@medusajs/framework/http"
183 import myWorkflow from "../../workflows/hello-world"
184
185 export async function GET(
186 req: MedusaRequest,
187 res: MedusaResponse
188 ) {
189 const { result } = await myWorkflow(req.scope)
190 .run({
191 input: {
192 name: req.query.name as string,
193 },
194 })
195
196 res.send(result)
197 }
198 ```
199
200 Learn more in [this documentation](!docs!/learn/fundamentals/workflows#3-execute-the-workflow).
201
202 ### Change Response Content Type
203
204 By default, an API route's response has the content type `application/json`.
205
206 To change it to another content type, use the `writeHead` method of `MedusaResponse`:
207
208 export const responseContentTypeHighlights = [
209 ["7", "writeHead", "Change the content type in the header."]
210 ]
211
212 ```ts highlights={responseContentTypeHighlights}
213 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
214
215 export const GET = async (
216 req: MedusaRequest,
217 res: MedusaResponse
218 ) => {
219 res.writeHead(200, {
220 "Content-Type": "text/event-stream",
221 "Cache-Control": "no-cache",
222 Connection: "keep-alive",
223 })
224
225 const interval = setInterval(() => {
226 res.write("Streaming data...\n")
227 }, 3000)
228
229 req.on("end", () => {
230 clearInterval(interval)
231 res.end()
232 })
233 }
234 ```
235
236 This changes the response type to return an event stream.
237
238 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/responses#change-response-content-type).
239
240 ### Create Middleware
241
242 A middleware is a function executed when a request is sent to an API Route.
243
244 Create the file `src/api/middlewares.ts` with the following content:
245
246 ```ts title="src/api/middlewares.ts"
247 import type {
248 MedusaNextFunction,
249 MedusaRequest,
250 MedusaResponse,
251 defineMiddlewares,
252 } from "@medusajs/framework/http"
253
254 export default defineMiddlewares({
255 routes: [
256 {
257 matcher: "/custom*",
258 middlewares: [
259 (
260 req: MedusaRequest,
261 res: MedusaResponse,
262 next: MedusaNextFunction
263 ) => {
264 console.log("Received a request!")
265
266 next()
267 },
268 ],
269 },
270 {
271 matcher: "/custom/:id",
272 middlewares: [
273 (
274 req: MedusaRequest,
275 res: MedusaResponse,
276 next: MedusaNextFunction
277 ) => {
278 console.log("With Path Parameter")
279
280 next()
281 },
282 ],
283 },
284 ],
285 })
286 ```
287
288 Learn more about middlewares in [this documentation](!docs!/learn/fundamentals/api-routes/middlewares).
289
290 ### Restrict HTTP Methods in Middleware
291
292 To restrict a middleware to an HTTP method:
293
294 export const middlewareMethodHighlights = [
295 ["12", "method", "Apply the middleware on `POST` and `PUT` requests only."]
296 ]
297
298 ```ts title="src/api/middlewares.ts" highlights={middlewareMethodHighlights}
299 import type {
300 MedusaNextFunction,
301 MedusaRequest,
302 MedusaResponse,
303 defineMiddlewares,
304 } from "@medusajs/framework/http"
305
306 export default defineMiddlewares({
307 routes: [
308 {
309 matcher: "/custom*",
310 method: ["POST", "PUT"],
311 middlewares: [
312 // ...
313 ],
314 },
315 ],
316 })
317 ```
318
319 ### Add Validation for Custom Routes
320
321 1. Create a [Zod](https://zod.dev/) schema in the file `src/api/custom/validators.ts`:
322
323 <Note>
324
325 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
326
327 </Note>
328
329 ```ts title="src/api/custom/validators.ts"
330 import { z } from "@medusajs/framework/zod"
331
332 export const PostStoreCustomSchema = z.object({
333 a: z.number(),
334 b: z.number(),
335 })
336 ```
337
338 2. Add a validation middleware to the custom route in `src/api/middlewares.ts`:
339
340 ```ts title="src/api/middlewares.ts" highlights={[["13", "validateAndTransformBody"]]}
341 import {
342 validateAndTransformBody,
343 defineMiddlewares,
344 } from "@medusajs/framework/http"
345 import { PostStoreCustomSchema } from "./custom/validators"
346
347 export default defineMiddlewares({
348 routes: [
349 {
350 matcher: "/custom",
351 method: "POST",
352 middlewares: [
353 validateAndTransformBody(PostStoreCustomSchema),
354 ],
355 },
356 ],
357 })
358 ```
359
360 3. Use the validated body in the `/custom` API route:
361
362 ```ts title="src/api/custom/route.ts" highlights={[["14", "validatedBody"]]}
363 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
364 import { z } from "@medusajs/framework/zod"
365 import { PostStoreCustomSchema } from "./validators"
366
367 type PostStoreCustomSchemaType = z.infer<
368 typeof PostStoreCustomSchema
369 >
370
371 export const POST = async (
372 req: MedusaRequest<PostStoreCustomSchemaType>,
373 res: MedusaResponse
374 ) => {
375 res.json({
376 sum: req.validatedBody.a + req.validatedBody.b,
377 })
378 }
379 ```
380
381 Learn more about request body validation in [this documentation](!docs!/learn/fundamentals/api-routes/validation).
382
383 ### Pass Additional Data to API Route
384
385 In this example, you'll pass additional data to the Create Product API route, then consume its hook:
386
387 <Note>
388
389 Find this example in details in [this documentation](!docs!/learn/customization/extend-features/extend-create-product).
390
391 </Note>
392
393 1. Create the file `src/api/middlewares.ts` with the following content:
394
395 ```ts title="src/api/middlewares.ts" highlights={[["10", "brand_id", "Replace with your custom field."]]}
396 import { defineMiddlewares } from "@medusajs/framework/http"
397 import { z } from "@medusajs/framework/zod"
398
399 export default defineMiddlewares({
400 routes: [
401 {
402 matcher: "/admin/products",
403 method: ["POST"],
404 additionalDataValidator: {
405 brand_id: z.string().optional(),
406 },
407 },
408 ],
409 })
410 ```
411
412 <Note>
413
414 Learn more about additional data in [this documentation](!docs!/learn/fundamentals/api-routes/additional-data).
415
416 </Note>
417
418 2. Create the file `src/workflows/hooks/created-product.ts` with the following content:
419
420 ```ts
421 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
422 import { StepResponse } from "@medusajs/framework/workflows-sdk"
423
424 createProductsWorkflow.hooks.productsCreated(
425 (async ({ products, additional_data }, { container }) => {
426 if (!additional_data.brand_id) {
427 return new StepResponse([], [])
428 }
429
430 // TODO perform custom action
431 }),
432 (async (links, { container }) => {
433 // TODO undo the action in the compensation
434 })
435
436 )
437 ```
438
439 <Note>
440
441 Learn more about workflow hooks in [this documentation](!docs!/learn/fundamentals/workflows/workflow-hooks).
442
443 </Note>
444
445 ### Restrict an API Route to Admin Users
446
447 You can protect API routes by restricting access to authenticated admin users only.
448
449 Add the following middleware in `src/api/middlewares.ts`:
450
451 ```ts title="src/api/middlewares.ts" highlights={[["11", "authenticate"]]}
452 import {
453 defineMiddlewares,
454 authenticate,
455 } from "@medusajs/framework/http"
456
457 export default defineMiddlewares({
458 routes: [
459 {
460 matcher: "/custom/admin*",
461 middlewares: [
462 authenticate(
463 "user",
464 ["session", "bearer", "api-key"]
465 ),
466 ],
467 },
468 ],
469 })
470 ```
471
472 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/protected-routes).
473
474 ### Restrict an API Route to Logged-In Customers
475
476 You can protect API routes by restricting access to authenticated customers only.
477
478 Add the following middleware in `src/api/middlewares.ts`:
479
480 ```ts title="src/api/middlewares.ts" highlights={[["11", "authenticate"]]}
481 import {
482 defineMiddlewares,
483 authenticate,
484 } from "@medusajs/framework/http"
485
486 export default defineMiddlewares({
487 routes: [
488 {
489 matcher: "/custom/customer*",
490 middlewares: [
491 authenticate("customer", ["session", "bearer"]),
492 ],
493 },
494 ],
495 })
496 ```
497
498 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/protected-routes).
499
500 ### Retrieve Logged-In Admin User
501
502 To retrieve the currently logged-in user in an API route:
503
504 <Note>
505
506 Requires setting up the authentication middleware as explained in [this example](#restrict-an-api-route-to-admin-users).
507
508 </Note>
509
510 ```ts highlights={[["16", "req.auth_context.actor_id", "Access the user's ID."]]}
511 import type {
512 AuthenticatedMedusaRequest,
513 MedusaResponse,
514 } from "@medusajs/framework/http"
515 import { Modules } from "@medusajs/framework/utils"
516
517 export const GET = async (
518 req: AuthenticatedMedusaRequest,
519 res: MedusaResponse
520 ) => {
521 const userModuleService = req.scope.resolve(
522 Modules.USER
523 )
524
525 const user = await userModuleService.retrieveUser(
526 req.auth_context.actor_id
527 )
528
529 // ...
530 }
531 ```
532
533 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/protected-routes#retrieve-logged-in-admin-users-details).
534
535 ### Retrieve Logged-In Customer
536
537 To retrieve the currently logged-in customer in an API route:
538
539 <Note>
540
541 Requires setting up the authentication middleware as explained in [this example](#restrict-an-api-route-to-logged-in-customers).
542
543 </Note>
544
545 ```ts highlights={[["18", "req.auth_context.actor_id", "Access the customer's ID."]]}
546 import type {
547 AuthenticatedMedusaRequest,
548 MedusaResponse,
549 } from "@medusajs/framework/http"
550 import { Modules } from "@medusajs/framework/utils"
551
552 export const GET = async (
553 req: AuthenticatedMedusaRequest,
554 res: MedusaResponse
555 ) => {
556 if (req.auth_context?.actor_id) {
557 // retrieve customer
558 const customerModuleService = req.scope.resolve(
559 Modules.CUSTOMER
560 )
561
562 const customer = await customerModuleService.retrieveCustomer(
563 req.auth_context.actor_id
564 )
565 }
566
567 // ...
568 }
569 ```
570
571 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/protected-routes#retrieve-logged-in-customers-details).
572
573 ### Throw Errors in API Route
574
575 To throw errors in an API route, use `MedusaError` from the Medusa Framework:
576
577 ```ts highlights={[["9", "MedusaError"]]}
578 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
579 import { MedusaError } from "@medusajs/framework/utils"
580
581 export const GET = async (
582 req: MedusaRequest,
583 res: MedusaResponse
584 ) => {
585 if (!req.query.q) {
586 throw new MedusaError(
587 MedusaError.Types.INVALID_DATA,
588 "The `q` query parameter is required."
589 )
590 }
591
592 // ...
593 }
594 ```
595
596 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/errors).
597
598 ### Override Error Handler of API Routes
599
600 To override the error handler of API routes, create the file `src/api/middlewares.ts` with the following content:
601
602 ```ts title="src/api/middlewares.ts" highlights={[["10", "errorHandler"]]}
603 import {
604 defineMiddlewares,
605 MedusaNextFunction,
606 MedusaRequest,
607 MedusaResponse,
608 } from "@medusajs/framework/http"
609 import { MedusaError } from "@medusajs/framework/utils"
610
611 export default defineMiddlewares({
612 errorHandler: (
613 error: MedusaError | any,
614 req: MedusaRequest,
615 res: MedusaResponse,
616 next: MedusaNextFunction
617 ) => {
618 res.status(400).json({
619 error: "Something happened.",
620 })
621 },
622 })
623 ```
624
625 Learn more in [this documentation](!docs!/learn/fundamentals/api-routes/errors#override-error-handler),
626
627 ### Setting up CORS for Custom API Routes
628
629 By default, Medusa configures CORS for all routes starting with `/admin`, `/store`, and `/auth`.
630
631 To configure CORS for routes under other prefixes, create the file `src/api/middlewares.ts` with the following content:
632
633 ```ts title="src/api/middlewares.ts"
634 import type {
635 MedusaNextFunction,
636 MedusaRequest,
637 MedusaResponse,
638 defineMiddlewares,
639 } from "@medusajs/framework/http"
640 import { ConfigModule } from "@medusajs/framework/types"
641 import {
642 parseCorsOrigins,
643 ContainerRegistrationKeys,
644 } from "@medusajs/framework/utils"
645 import cors from "cors"
646
647 export default defineMiddlewares({
648 routes: [
649 {
650 matcher: "/custom*",
651 middlewares: [
652 (
653 req: MedusaRequest,
654 res: MedusaResponse,
655 next: MedusaNextFunction
656 ) => {
657 const configModule: ConfigModule =
658 req.scope.resolve(
659 ContainerRegistrationKeys.CONFIG_MODULE
660 )
661
662 return cors({
663 origin: parseCorsOrigins(
664 configModule.projectConfig.http.storeCors
665 ),
666 credentials: true,
667 })(req, res, next)
668 },
669 ],
670 },
671 ],
672 })
673 ```
674
675 ### Parse Webhook Body
676
677 By default, the Medusa application parses a request's body using JSON.
678
679 To parse a webhook's body, create the file `src/api/middlewares.ts` with the following content:
680
681 ```ts title="src/api/middlewares.ts" highlights={[["9"]]}
682 import {
683 defineMiddlewares,
684 } from "@medusajs/framework/http"
685
686 export default defineMiddlewares({
687 routes: [
688 {
689 matcher: "/webhooks/*",
690 bodyParser: { preserveRawBody: true },
691 method: ["POST"],
692 },
693 ],
694 })
695 ```
696
697 To access the raw body data in your route, use the `req.rawBody` property:
698
699 ```ts title="src/api/webhooks/route.ts"
700 import type {
701 MedusaRequest,
702 MedusaResponse,
703 } from "@medusajs/framework/http"
704
705 export const POST = (
706 req: MedusaRequest,
707 res: MedusaResponse
708 ) => {
709 console.log(req.rawBody)
710 }
711 ```
712
713 ---
714
715 ## Modules
716
717 A module is a package of reusable commerce or architectural functionalities. They handle business logic in a class called a service, and define and manage data models that represent tables in the database.
718
719 ### Create Module
720
721 <Note>
722
723 Find this example explained in details in [this documentation](!docs!/learn/fundamentals/modules).
724
725 </Note>
726
727 1. Create the directory `src/modules/blog`.
728 2. Create the file `src/modules/blog/models/post.ts` with the following data model:
729
730 ```ts title="src/modules/blog/models/post.ts"
731 import { model } from "@medusajs/framework/utils"
732
733 const Post = model.define("post", {
734 id: model.id().primaryKey(),
735 title: model.text(),
736 })
737
738 export default Post
739 ```
740
741 3. Create the file `src/modules/blog/service.ts` with the following service:
742
743 ```ts title="src/modules/blog/service.ts"
744 import { MedusaService } from "@medusajs/framework/utils"
745 import Post from "./models/post"
746
747 class BlogModuleService extends MedusaService({
748 Post,
749 }){
750 }
751
752 export default BlogModuleService
753 ```
754
755 4. Create the file `src/modules/blog/index.ts` that exports the module definition:
756
757 ```ts title="src/modules/blog/index.ts"
758 import BlogModuleService from "./service"
759 import { Module } from "@medusajs/framework/utils"
760
761 export const BLOG_MODULE = "blog"
762
763 export default Module(BLOG_MODULE, {
764 service: BlogModuleService,
765 })
766 ```
767
768 5. Add the module to the configurations in `medusa-config.ts`:
769
770 ```ts title="medusa-config.ts"
771 module.exports = defineConfig({
772 projectConfig: {
773 // ...
774 },
775 modules: [
776 {
777 resolve: "./modules/blog",
778 },
779 ],
780 })
781 ```
782
783 6. Generate and run migrations:
784
785 ```bash npx2yarn
786 npx medusa db:generate blog
787 npx medusa db:migrate
788 ```
789
790 7. Create a workflow that uses the module's main service in a step in the file `src/workflows/create-post.ts`:
791
792 ```ts title="src/workflows/create-post.ts"
793 import {
794 createStep,
795 createWorkflow,
796 StepResponse,
797 WorkflowResponse,
798 } from "@medusajs/framework/workflows-sdk"
799 import BlogModuleService from "../modules/blog/service"
800 import { BLOG_MODULE } from "../modules/blog"
801
802 type CreatePostInput = {
803 title: string
804 }
805
806 const createPostStep = createStep(
807 "create-post",
808 async (input: CreatePostInput, { container }) => {
809 const blogModuleService: BlogModuleService =
810 container.resolve(BLOG_MODULE)
811
812 const post = await blogModuleService.createPosts(input)
813
814 return new StepResponse(post, post.id)
815 },
816 async (postId, { container }) => {
817 if (!postId) {
818 return
819 }
820
821 const blogModuleService: BlogModuleService =
822 container.resolve(BLOG_MODULE)
823
824 await blogModuleService.deletePosts(postId)
825 }
826 )
827
828 const createPostWorkflow = createWorkflow(
829 "create-post",
830 (input: CreatePostInput) => {
831 const post = createPostStep(input)
832
833 return new WorkflowResponse(post)
834 }
835 )
836
837 export default createPostWorkflow
838 ```
839
840 8. Execute the workflow in an API route:
841
842 ```ts title="src/api/custom/route.ts"
843 import {
844 MedusaRequest,
845 MedusaResponse,
846 } from "@medusajs/framework/http"
847 import createPostWorkflow from "../../workflows/create-post"
848
849 export async function POST(
850 req: MedusaRequest,
851 res: MedusaResponse
852 ): Promise<void> {
853 const { result: post } = await createPostWorkflow(req.scope)
854 .run({
855 input: {
856 title: "test",
857 },
858 })
859
860 res.json({
861 post,
862 })
863 }
864 ```
865
866 ### Module with Multiple Services
867
868 To add services in your module other than the main one, create them in the `services` directory of the module.
869
870 For example, create the file `src/modules/blog/services/category.ts` with the following content:
871
872 ```ts title="src/modules/blog/services/category.ts"
873 export class CategoryService {
874 // TODO add methods
875 }
876 ```
877
878 Then, export the service in the file `src/modules/blog/services/index.ts`:
879
880 ```ts title="src/modules/blog/services/index.ts"
881 export * from "./category"
882 ```
883
884 Finally, resolve the service in your module's main service or loader:
885
886 ```ts title="src/modules/blog/service.ts"
887 import { MedusaService } from "@medusajs/framework/utils"
888 import Post from "./models/post"
889 import { CategoryService } from "./services"
890
891 type InjectedDependencies = {
892 categoryService: CategoryService
893 }
894
895 class BlogModuleService extends MedusaService({
896 Post,
897 }){
898 private categoryService: CategoryService
899
900 constructor({ categoryService }: InjectedDependencies) {
901 super(...arguments)
902
903 this.categoryService = categoryService
904 }
905 }
906
907 export default BlogModuleService
908 ```
909
910 Learn more in [this documentation](!docs!/learn/fundamentals/modules/multiple-services).
911
912 ### Accept Module Options
913
914 A module can accept options for configurations and secrets.
915
916 To accept options in your module:
917
918 1. Pass options to the module in `medusa-config.ts`:
919
920 ```ts title="medusa-config.ts" highlights={[["6", "options"]]}
921 module.exports = defineConfig({
922 // ...
923 modules: [
924 {
925 resolve: "./modules/blog",
926 options: {
927 apiKey: true,
928 },
929 },
930 ],
931 })
932 ```
933
934 2. Access the options in the module's main service:
935
936 ```ts title="src/modules/blog/service.ts" highlights={[["14", "options"]]}
937 import { MedusaService } from "@medusajs/framework/utils"
938 import Post from "./models/post"
939
940 // recommended to define type in another file
941 type ModuleOptions = {
942 apiKey?: boolean
943 }
944
945 export default class BlogModuleService extends MedusaService({
946 Post,
947 }){
948 protected options_: ModuleOptions
949
950 constructor({}, options?: ModuleOptions) {
951 super(...arguments)
952
953 this.options_ = options || {
954 apiKey: false,
955 }
956 }
957
958 // ...
959 }
960 ```
961
962 Learn more in [this documentation](!docs!/learn/fundamentals/modules/options).
963
964 ### Integrate Third-Party System in Module
965
966 An example of integrating a dummy third-party system in a module's service:
967
968 ```ts title="src/modules/blog/service.ts"
969 import { Logger } from "@medusajs/framework/types"
970 import { BLOG_MODULE } from ".."
971
972 export type ModuleOptions = {
973 apiKey: string
974 }
975
976 type InjectedDependencies = {
977 logger: Logger
978 }
979
980 export class BlogClient {
981 private options_: ModuleOptions
982 private logger_: Logger
983
984 constructor(
985 { logger }: InjectedDependencies,
986 options: ModuleOptions
987 ) {
988 this.logger_ = logger
989 this.options_ = options
990 }
991
992 private async sendRequest(url: string, method: string, data?: any) {
993 this.logger_.info(`Sending a ${
994 method
995 } request to ${url}. data: ${JSON.stringify(data, null, 2)}`)
996 this.logger_.info(`Client Options: ${
997 JSON.stringify(this.options_, null, 2)
998 }`)
999 }
1000 }
1001 ```
1002
1003 Find a longer example of integrating a third-party service in [this documentation](!docs!/learn/customization/integrate-systems/service).
1004
1005 ---
1006
1007 ## Data Models
1008
1009 A data model represents a table in the database. Medusa provides a data model language to intuitively create data models.
1010
1011 ### Create Data Model
1012
1013 To create a data model in a module:
1014
1015 <Note>
1016
1017 This assumes you already have a module. If not, follow [this example](#create-module).
1018
1019 </Note>
1020
1021 1. Create the file `src/modules/blog/models/post.ts` with the following data model:
1022
1023 ```ts title="src/modules/blog/models/post.ts"
1024 import { model } from "@medusajs/framework/utils"
1025
1026 const Post = model.define("post", {
1027 id: model.id().primaryKey(),
1028 title: model.text(),
1029 })
1030
1031 export default Post
1032 ```
1033
1034 2. Generate and run migrations:
1035
1036 ```bash npx2yarn
1037 npx medusa db:generate blog
1038 npx medusa db:migrate
1039 ```
1040
1041 Learn more in [this documentation](!docs!/learn/fundamentals/modules#1-create-data-model).
1042
1043 ### Data Model Property Types
1044
1045 A data model can have properties of the following types:
1046
1047 1. ID property:
1048
1049 ```ts
1050 const Post = model.define("post", {
1051 id: model.id(),
1052 // ...
1053 })
1054 ```
1055
1056 2. Text property:
1057
1058 ```ts
1059 const Post = model.define("post", {
1060 title: model.text(),
1061 // ...
1062 })
1063 ```
1064
1065 3. Number property:
1066
1067 ```ts
1068 const Post = model.define("post", {
1069 views: model.number(),
1070 // ...
1071 })
1072 ```
1073
1074 4. Big Number property:
1075
1076 ```ts
1077 const Post = model.define("post", {
1078 price: model.bigNumber(),
1079 // ...
1080 })
1081 ```
1082
1083 5. Boolean property:
1084
1085 ```ts
1086 const Post = model.define("post", {
1087 isPublished: model.boolean(),
1088 // ...
1089 })
1090 ```
1091
1092 6. Enum property:
1093
1094 ```ts
1095 const Post = model.define("post", {
1096 status: model.enum(["draft", "published"]),
1097 // ...
1098 })
1099 ```
1100
1101 7. Date-Time property:
1102
1103 ```ts
1104 const Post = model.define("post", {
1105 publishedAt: model.dateTime(),
1106 // ...
1107 })
1108 ```
1109
1110 8. JSON property:
1111
1112 ```ts
1113 const Post = model.define("post", {
1114 metadata: model.json(),
1115 // ...
1116 })
1117 ```
1118
1119 9. Array property:
1120
1121 ```ts
1122 const Post = model.define("post", {
1123 tags: model.array(),
1124 // ...
1125 })
1126 ```
1127
1128 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties).
1129
1130 ### Set Primary Key
1131
1132 To set an `id` property as the primary key of a data model:
1133
1134 ```ts highlights={[["4", "primaryKey"]]}
1135 import { model } from "@medusajs/framework/utils"
1136
1137 const Post = model.define("post", {
1138 id: model.id().primaryKey(),
1139 // ...
1140 })
1141
1142 export default Post
1143 ```
1144
1145 To set a `text` property as the primary key:
1146
1147 ```ts highlights={[["4", "primaryKey"]]}
1148 import { model } from "@medusajs/framework/utils"
1149
1150 const Post = model.define("post", {
1151 title: model.text().primaryKey(),
1152 // ...
1153 })
1154
1155 export default Post
1156 ```
1157
1158 To set a `number` property as the primary key:
1159
1160 ```ts highlights={[["4", "primaryKey"]]}
1161 import { model } from "@medusajs/framework/utils"
1162
1163 const Post = model.define("post", {
1164 views: model.number().primaryKey(),
1165 // ...
1166 })
1167
1168 export default Post
1169 ```
1170
1171 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#set-primary-key-property).
1172
1173 ### Default Property Value
1174
1175 To set the default value of a property:
1176
1177 ```ts highlights={[["6"], ["9"]]}
1178 import { model } from "@medusajs/framework/utils"
1179
1180 const Post = model.define("post", {
1181 status: model
1182 .enum(["draft", "published"])
1183 .default("draft"),
1184 views: model
1185 .number()
1186 .default(0),
1187 // ...
1188 })
1189
1190 export default Post
1191 ```
1192
1193 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#property-default-value).
1194
1195 ### Nullable Property
1196
1197 To allow `null` values for a property:
1198
1199 ```ts highlights={[["4", "nullable"]]}
1200 import { model } from "@medusajs/framework/utils"
1201
1202 const Post = model.define("post", {
1203 price: model.bigNumber().nullable(),
1204 // ...
1205 })
1206
1207 export default Post
1208 ```
1209
1210 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#make-property-optional).
1211
1212 ### Unique Property
1213
1214 To create a unique index on a property:
1215
1216 ```ts highlights={[["4", "unique"]]}
1217 import { model } from "@medusajs/framework/utils"
1218
1219 const Post = model.define("post", {
1220 title: model.text().unique(),
1221 // ...
1222 })
1223
1224 export default Post
1225 ```
1226
1227 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#unique-property).
1228
1229 ### Define Database Index on Property
1230
1231 To define a database index on a property:
1232
1233 ```ts highlights={[["5", "index"]]}
1234 import { model } from "@medusajs/framework/utils"
1235
1236 const MyCustom = model.define("my_custom", {
1237 id: model.id().primaryKey(),
1238 title: model.text().index(
1239 "IDX_POST_TITLE"
1240 ),
1241 })
1242
1243 export default MyCustom
1244 ```
1245
1246 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#define-database-index-on-property).
1247
1248 ### Define Composite Index on Data Model
1249
1250 To define a composite index on a data model:
1251
1252 ```ts highlights={[["7", "indexes"]]}
1253 import { model } from "@medusajs/framework/utils"
1254
1255 const MyCustom = model.define("my_custom", {
1256 id: model.id().primaryKey(),
1257 name: model.text(),
1258 age: model.number().nullable(),
1259 }).indexes([
1260 {
1261 on: ["name", "age"],
1262 where: {
1263 age: {
1264 $ne: null,
1265 },
1266 },
1267 },
1268 ])
1269
1270 export default MyCustom
1271 ```
1272
1273 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/indexes).
1274
1275 ### Make a Property Searchable
1276
1277 To make a property searchable using terms or keywords:
1278
1279 ```ts highlights={[["4", "searchable"]]}
1280 import { model } from "@medusajs/framework/utils"
1281
1282 const Post = model.define("post", {
1283 title: model.text().searchable(),
1284 // ...
1285 })
1286
1287 export default Post
1288 ```
1289
1290 Then, to search by that property, pass the `q` filter to the `list` or `listAndCount` generated methods of the module's main service:
1291
1292 <Note>
1293
1294 `blogModuleService` is the main service that manages the `Post` data model.
1295
1296 </Note>
1297
1298 ```ts
1299 const posts = await blogModuleService.listPosts({
1300 q: "John",
1301 })
1302 ```
1303
1304 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/properties#searchable-property).
1305
1306 ### Create One-to-One Relationship
1307
1308 The following creates a one-to-one relationship between the `User` and `Email` data models:
1309
1310 ```ts highlights={[["5", "hasOne"], ["12", "belongsTo"]]}
1311 import { model } from "@medusajs/framework/utils"
1312
1313 const User = model.define("user", {
1314 id: model.id().primaryKey(),
1315 email: model.hasOne(() => Email, {
1316 mappedBy: "user",
1317 }),
1318 })
1319
1320 const Email = model.define("email", {
1321 id: model.id().primaryKey(),
1322 user: model.belongsTo(() => User, {
1323 mappedBy: "email",
1324 }),
1325 })
1326 ```
1327
1328 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/relationships#one-to-one-relationship).
1329
1330 ### Create One-to-Many Relationship
1331
1332 The following creates a one-to-many relationship between the `Store` and `Product` data models:
1333
1334 ```ts highlights={[["5", "hasMany"], ["12", "belongsTo"]]}
1335 import { model } from "@medusajs/framework/utils"
1336
1337 const Store = model.define("store", {
1338 id: model.id().primaryKey(),
1339 products: model.hasMany(() => Product, {
1340 mappedBy: "store",
1341 }),
1342 })
1343
1344 const Product = model.define("product", {
1345 id: model.id().primaryKey(),
1346 store: model.belongsTo(() => Store, {
1347 mappedBy: "products",
1348 }),
1349 })
1350 ```
1351
1352 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/relationships#one-to-many-relationship).
1353
1354 ### Create Many-to-Many Relationship
1355
1356 The following creates a many-to-many relationship between the `Order` and `Product` data models:
1357
1358 ```ts highlights={[["5", "manyToMany"], ["12", "manyToMany"]]}
1359 import { model } from "@medusajs/framework/utils"
1360
1361 const Order = model.define("order", {
1362 id: model.id().primaryKey(),
1363 products: model.manyToMany(() => Product, {
1364 mappedBy: "orders",
1365 }),
1366 })
1367
1368 const Product = model.define("product", {
1369 id: model.id().primaryKey(),
1370 orders: model.manyToMany(() => Order, {
1371 mappedBy: "products",
1372 }),
1373 })
1374 ```
1375
1376 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/relationships#many-to-many-relationship).
1377
1378 ### Configure Cascades of Data Model
1379
1380 To configure cascade on a data model:
1381
1382 ```ts highlights={[["10", "cascades"]]}
1383 import { model } from "@medusajs/framework/utils"
1384 import Product from "./product"
1385
1386 const Store = model.define("store", {
1387 id: model.id().primaryKey(),
1388 products: model.hasMany(() => Product, {
1389 mappedBy: "store",
1390 }),
1391 })
1392 .cascades({
1393 delete: ["products"],
1394 })
1395 ```
1396
1397 This configures the delete cascade on the `Store` data model so that, when a store is delete, its products are also deleted.
1398
1399 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/relationships#cascades).
1400
1401
1402 ### Manage One-to-One Relationship
1403
1404 Consider you have a one-to-one relationship between `Email` and `User` data models, where an email belongs to a user.
1405
1406 To set the ID of the user that an email belongs to:
1407
1408 <Note>
1409
1410 `blogModuleService` is the main service that manages the `Email` and `User` data models.
1411
1412 </Note>
1413
1414 ```ts
1415 // when creating an email
1416 const email = await blogModuleService.createEmails({
1417 // other properties...
1418 user: "123",
1419 })
1420
1421 // when updating an email
1422 const email = await blogModuleService.updateEmails({
1423 id: "321",
1424 // other properties...
1425 user: "123",
1426 })
1427 ```
1428
1429 And to set the ID of a user's email when creating or updating it:
1430
1431 ```ts
1432 // when creating a user
1433 const user = await blogModuleService.createUsers({
1434 // other properties...
1435 email: "123",
1436 })
1437
1438 // when updating a user
1439 const user = await blogModuleService.updateUsers({
1440 id: "321",
1441 // other properties...
1442 email: "123",
1443 })
1444 ```
1445
1446 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/manage-relationships#manage-one-to-one-relationship).
1447
1448 ### Manage One-to-Many Relationship
1449
1450 Consider you have a one-to-many relationship between `Product` and `Store` data models, where a store has many products.
1451
1452 To set the ID of the store that a product belongs to:
1453
1454 <Note>
1455
1456 `blogModuleService` is the main service that manages the `Product` and `Store` data models.
1457
1458 </Note>
1459
1460 ```ts
1461 // when creating a product
1462 const product = await blogModuleService.createProducts({
1463 // other properties...
1464 store_id: "123",
1465 })
1466
1467 // when updating a product
1468 const product = await blogModuleService.updateProducts({
1469 id: "321",
1470 // other properties...
1471 store_id: "123",
1472 })
1473 ```
1474
1475 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/manage-relationships#manage-one-to-many-relationship)
1476
1477 ### Manage Many-to-Many Relationship
1478
1479 Consider you have a many-to-many relationship between `Order` and `Product` data models.
1480
1481 To set the orders a product has when creating it:
1482
1483 <Note>
1484
1485 `blogModuleService` is the main service that manages the `Product` and `Order` data models.
1486
1487 </Note>
1488
1489 ```ts
1490 const product = await blogModuleService.createProducts({
1491 // other properties...
1492 orders: ["123", "321"],
1493 })
1494 ```
1495
1496 To add new orders to a product without removing the previous associations:
1497
1498 ```ts
1499 const product = await blogModuleService.retrieveProduct(
1500 "123",
1501 {
1502 relations: ["orders"],
1503 }
1504 )
1505
1506 const updatedProduct = await blogModuleService.updateProducts({
1507 id: product.id,
1508 // other properties...
1509 orders: [
1510 ...product.orders.map((order) => order.id),
1511 "321",
1512 ],
1513 })
1514 ```
1515
1516 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/manage-relationships#manage-many-to-many-relationship).
1517
1518 ### Retrieve Related Records
1519
1520 To retrieve records related to a data model's records through a relation, pass the `relations` field to the `list`, `listAndCount`, or `retrieve` generated methods:
1521
1522 <Note>
1523
1524 `blogModuleService` is the main service that manages the `Product` and `Order` data models.
1525
1526 </Note>
1527
1528 ```ts highlights={[["4", "relations"]]}
1529 const product = await blogModuleService.retrieveProducts(
1530 "123",
1531 {
1532 relations: ["orders"],
1533 }
1534 )
1535 ```
1536
1537 Learn more in [this documentation](!docs!/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation).
1538
1539 ---
1540
1541 ## Services
1542
1543 A service is the main resource in a module. It manages the records of your custom data models in the database, or integrate third-party systems.
1544
1545 ### Extend Service Factory
1546
1547 The service factory `MedusaService` generates data-management methods for your data models.
1548
1549 To extend the service factory in your module's service:
1550
1551 ```ts highlights={[["4", "MedusaService"]]}
1552 import { MedusaService } from "@medusajs/framework/utils"
1553 import Post from "./models/post"
1554
1555 class BlogModuleService extends MedusaService({
1556 Post,
1557 }){
1558 // TODO implement custom methods
1559 }
1560
1561 export default BlogModuleService
1562 ```
1563
1564 The `BlogModuleService` will now have data-management methods for `Post`.
1565
1566 Refer to [this reference](../service-factory-reference/page.mdx) for details on the generated methods.
1567
1568 Learn more about the service factory in [this documentation](!docs!/learn/fundamentals/modules/service-factory).
1569
1570 ### Resolve Resources in the Service
1571
1572 To resolve resources from the module's container in a service:
1573
1574 <CodeTabs group="service-type">
1575 <CodeTab label="With Service Factory" value="service-factory">
1576
1577 ```ts highlights={[["14"]]}
1578 import { Logger } from "@medusajs/framework/types"
1579 import { MedusaService } from "@medusajs/framework/utils"
1580 import Post from "./models/post"
1581
1582 type InjectedDependencies = {
1583 logger: Logger
1584 }
1585
1586 class BlogModuleService extends MedusaService({
1587 Post,
1588 }){
1589 protected logger_: Logger
1590
1591 constructor({ logger }: InjectedDependencies) {
1592 super(...arguments)
1593 this.logger_ = logger
1594
1595 this.logger_.info("[BlogModuleService]: Hello World!")
1596 }
1597
1598 // ...
1599 }
1600
1601 export default BlogModuleService
1602 ```
1603
1604 </CodeTab>
1605 <CodeTab label="Without Service Factory" value="no-service-factory">
1606
1607 ```ts highlights={[["10"]]}
1608 import { Logger } from "@medusajs/framework/types"
1609
1610 type InjectedDependencies = {
1611 logger: Logger
1612 }
1613
1614 export default class BlogModuleService {
1615 protected logger_: Logger
1616
1617 constructor({ logger }: InjectedDependencies) {
1618 this.logger_ = logger
1619
1620 this.logger_.info("[BlogModuleService]: Hello World!")
1621 }
1622
1623 // ...
1624 }
1625 ```
1626
1627 </CodeTab>
1628 </CodeTabs>
1629
1630 Learn more in [this documentation](!docs!/learn/fundamentals/modules/container).
1631
1632 ### Access Module Options in Service
1633
1634 To access options passed to a module in its service:
1635
1636 ```ts highlights={[["14", "options"]]}
1637 import { MedusaService } from "@medusajs/framework/utils"
1638 import Post from "./models/post"
1639
1640 // recommended to define type in another file
1641 type ModuleOptions = {
1642 apiKey?: boolean
1643 }
1644
1645 export default class BlogModuleService extends MedusaService({
1646 Post,
1647 }){
1648 protected options_: ModuleOptions
1649
1650 constructor({}, options?: ModuleOptions) {
1651 super(...arguments)
1652
1653 this.options_ = options || {
1654 apiKey: "",
1655 }
1656 }
1657
1658 // ...
1659 }
1660 ```
1661
1662 Learn more in [this documentation](!docs!/learn/fundamentals/modules/options).
1663
1664 ### Run Database Query in Service
1665
1666 To run database query in your service:
1667
1668 ```ts highlights={[["14", "count"], ["21", "execute"]]}
1669 // other imports...
1670 import {
1671 InjectManager,
1672 MedusaContext,
1673 } from "@medusajs/framework/utils"
1674
1675 class BlogModuleService {
1676 // ...
1677
1678 @InjectManager()
1679 async getCount(
1680 @MedusaContext() sharedContext?: Context<EntityManager>
1681 ): Promise<number> {
1682 return await sharedContext.manager.count("post")
1683 }
1684
1685 @InjectManager()
1686 async getCountSql(
1687 @MedusaContext() sharedContext?: Context<EntityManager>
1688 ): Promise<number> {
1689 const data = await sharedContext.manager.execute(
1690 "SELECT COUNT(*) as num FROM post"
1691 )
1692
1693 return parseInt(data[0].num)
1694 }
1695 }
1696 ```
1697
1698 Learn more in [this documentation](!docs!/learn/fundamentals/modules/db-operations#run-queries)
1699
1700 ### Execute Database Operations in Transactions
1701
1702 To execute database operations within a transaction in your service:
1703
1704 ```ts
1705 import {
1706 InjectManager,
1707 InjectTransactionManager,
1708 MedusaContext,
1709 } from "@medusajs/framework/utils"
1710 import { Context } from "@medusajs/framework/types"
1711 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
1712
1713 class BlogModuleService {
1714 // ...
1715 @InjectTransactionManager()
1716 protected async update_(
1717 input: {
1718 id: string,
1719 name: string
1720 },
1721 @MedusaContext() sharedContext?: Context<EntityManager>
1722 ): Promise<any> {
1723 const transactionManager = sharedContext.transactionManager
1724 await transactionManager.nativeUpdate(
1725 "post",
1726 {
1727 id: input.id,
1728 },
1729 {
1730 name: input.name,
1731 }
1732 )
1733
1734 // retrieve again
1735 const updatedRecord = await transactionManager.execute(
1736 `SELECT * FROM post WHERE id = '${input.id}'`
1737 )
1738
1739 return updatedRecord
1740 }
1741
1742 @InjectManager()
1743 async update(
1744 input: {
1745 id: string,
1746 name: string
1747 },
1748 @MedusaContext() sharedContext?: Context<EntityManager>
1749 ) {
1750 return await this.update_(input, sharedContext)
1751 }
1752 }
1753 ```
1754
1755 Learn more in [this documentation](!docs!/learn/fundamentals/modules/db-operations#execute-operations-in-transactions).
1756
1757 ---
1758
1759 ## Module Links
1760
1761 A module link forms an association between two data models of different modules, while maintaining module isolation.
1762
1763 ### Define a Link
1764
1765 To define a link between your custom module and a Commerce Module, such as the Product Module:
1766
1767 1. Create the file `src/links/blog-product.ts` with the following content:
1768
1769 ```ts title="src/links/blog-product.ts"
1770 import BlogModule from "../modules/blog"
1771 import ProductModule from "@medusajs/medusa/product"
1772 import { defineLink } from "@medusajs/framework/utils"
1773
1774 export default defineLink(
1775 ProductModule.linkable.product,
1776 BlogModule.linkable.post
1777 )
1778 ```
1779
1780 2. Run the following command to sync the links:
1781
1782 ```bash npx2yarn
1783 npx medusa db:migrate
1784 ```
1785
1786 Learn more in [this documentation](!docs!/learn/fundamentals/module-links).
1787
1788 ### Define a List Link
1789
1790 To define a list link, where multiple records of a model can be linked to a record in another:
1791
1792 ```ts highlights={[["9", "isList"]]}
1793 import BlogModule from "../modules/blog"
1794 import ProductModule from "@medusajs/medusa/product"
1795 import { defineLink } from "@medusajs/framework/utils"
1796
1797 export default defineLink(
1798 ProductModule.linkable.product,
1799 {
1800 linkable: BlogModule.linkable.post,
1801 isList: true,
1802 }
1803 )
1804 ```
1805
1806 Learn more about list links in [this documentation](!docs!/learn/fundamentals/module-links#define-a-list-link).
1807
1808 ### Set Delete Cascade on Link Definition
1809
1810 To ensure a model's records linked to another model are deleted when the linked model is deleted:
1811
1812 ```ts highlights={[["9", "deleteCascade"]]}
1813 import BlogModule from "../modules/blog"
1814 import ProductModule from "@medusajs/medusa/product"
1815 import { defineLink } from "@medusajs/framework/utils"
1816
1817 export default defineLink(
1818 ProductModule.linkable.product,
1819 {
1820 linkable: BlogModule.linkable.post,
1821 deleteCascade: true,
1822 }
1823 )
1824 ```
1825
1826 Learn more in [this documentation](!docs!/learn/fundamentals/module-links#set-delete-cascades-on-link).
1827
1828 ### Add Custom Columns to Module Link
1829
1830 To add a custom column to the table that stores the linked records of two data models:
1831
1832 ```ts highlights={[["9", "database"]]}
1833 import BlogModule from "../modules/blog"
1834 import ProductModule from "@medusajs/medusa/product"
1835 import { defineLink } from "@medusajs/framework/utils"
1836
1837 export default defineLink(
1838 ProductModule.linkable.product,
1839 BlogModule.linkable.post,
1840 {
1841 database: {
1842 extraColumns: {
1843 metadata: {
1844 type: "json",
1845 },
1846 },
1847 },
1848 }
1849 )
1850 ```
1851
1852 Then, to set the custom column when creating or updating a link between records:
1853
1854 ```ts
1855 await link.create({
1856 [Modules.PRODUCT]: {
1857 product_id: "123",
1858 },
1859 HELLO_MODULE: {
1860 my_custom_id: "321",
1861 },
1862 data: {
1863 metadata: {
1864 test: true,
1865 },
1866 },
1867 })
1868 ```
1869
1870 To retrieve the custom column when retrieving linked records using Query:
1871
1872 ```ts
1873 import productBlogLink from "../links/product-blog"
1874
1875 // ...
1876
1877 const { data } = await query.graph({
1878 entity: productBlogLink.entryPoint,
1879 fields: ["metadata", "product.*", "post.*"],
1880 filters: {
1881 product_id: "prod_123",
1882 },
1883 })
1884 ```
1885
1886 Learn more in [this documentation](!docs!/learn/fundamentals/module-links/custom-columns).
1887
1888 ### Create Link Between Records
1889
1890 To create a link between two records using Link:
1891
1892 ```ts
1893 import { Modules } from "@medusajs/framework/utils"
1894 import { BLOG_MODULE } from "../../modules/blog"
1895
1896 // ...
1897
1898 await link.create({
1899 [Modules.PRODUCT]: {
1900 product_id: "prod_123",
1901 },
1902 [HELLO_MODULE]: {
1903 my_custom_id: "mc_123",
1904 },
1905 })
1906 ```
1907
1908 Learn more in [this documentation](!docs!/learn/fundamentals/module-links/link#create-link).
1909
1910 ### Dismiss Link Between Records
1911
1912 To dismiss links between records using Link:
1913
1914 ```ts
1915 import { Modules } from "@medusajs/framework/utils"
1916 import { BLOG_MODULE } from "../../modules/blog"
1917
1918 // ...
1919
1920 await link.dismiss({
1921 [Modules.PRODUCT]: {
1922 product_id: "prod_123",
1923 },
1924 [BLOG_MODULE]: {
1925 post_id: "mc_123",
1926 },
1927 })
1928 ```
1929
1930 Learn more in [this documentation](!docs!/learn/fundamentals/module-links/link#dismiss-link).
1931
1932 ### Cascade Delete Linked Records
1933
1934 To cascade delete records linked to a deleted record:
1935
1936 ```ts
1937 import { Modules } from "@medusajs/framework/utils"
1938
1939 // ...
1940
1941 await productModuleService.deleteVariants([variant.id])
1942
1943 await link.delete({
1944 [Modules.PRODUCT]: {
1945 product_id: "prod_123",
1946 },
1947 })
1948 ```
1949
1950 Learn more in [this documentation](!docs!/learn/fundamentals/module-links/link#cascade-delete-linked-records).
1951
1952 ### Restore Linked Records
1953
1954 To restore records that were soft-deleted because they were linked to a soft-deleted record:
1955
1956 ```ts
1957 import { Modules } from "@medusajs/framework/utils"
1958
1959 // ...
1960
1961 await productModuleService.restoreProducts(["prod_123"])
1962
1963 await link.restore({
1964 [Modules.PRODUCT]: {
1965 product_id: "prod_123",
1966 },
1967 })
1968 ```
1969
1970 Learn more in [this documentation](!docs!/learn/fundamentals/module-links/link#restore-linked-records).
1971
1972 ---
1973
1974 ## Query
1975
1976 Query fetches data across modules. It’s a set of methods registered in the Medusa container under the `query` key.
1977
1978 ### Retrieve Records of Data Model
1979
1980 To retrieve records using Query in an API route:
1981
1982 ```ts highlights={[["15", "graph"]]}
1983 import {
1984 MedusaRequest,
1985 MedusaResponse,
1986 } from "@medusajs/framework/http"
1987 import {
1988 ContainerRegistrationKeys,
1989 } from "@medusajs/framework/utils"
1990
1991 export const GET = async (
1992 req: MedusaRequest,
1993 res: MedusaResponse
1994 ) => {
1995 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1996
1997 const { data: myCustoms } = await query.graph({
1998 entity: "my_custom",
1999 fields: ["id", "name"],
2000 })
2001
2002 res.json({ my_customs: myCustoms })
2003 }
2004 ```
2005
2006 Learn more in [this documentation](!docs!/learn/fundamentals/query).
2007
2008 ### Retrieve Linked Records of Data Model
2009
2010 To retrieve records linked to a data model:
2011
2012 ```ts highlights={[["20"]]}
2013 import {
2014 MedusaRequest,
2015 MedusaResponse,
2016 } from "@medusajs/framework/http"
2017 import {
2018 ContainerRegistrationKeys,
2019 } from "@medusajs/framework/utils"
2020
2021 export const GET = async (
2022 req: MedusaRequest,
2023 res: MedusaResponse
2024 ) => {
2025 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
2026
2027 const { data: myCustoms } = await query.graph({
2028 entity: "my_custom",
2029 fields: [
2030 "id",
2031 "name",
2032 "product.*",
2033 ],
2034 })
2035
2036 res.json({ my_customs: myCustoms })
2037 }
2038 ```
2039
2040 Learn more in [this documentation](!docs!/learn/fundamentals/query#retrieve-linked-records).
2041
2042 ### Apply Filters to Retrieved Records
2043
2044 To filter the retrieved records:
2045
2046 ```ts highlights={[["18", "filters"]]}
2047 import {
2048 MedusaRequest,
2049 MedusaResponse,
2050 } from "@medusajs/framework/http"
2051 import {
2052 ContainerRegistrationKeys,
2053 } from "@medusajs/framework/utils"
2054
2055 export const GET = async (
2056 req: MedusaRequest,
2057 res: MedusaResponse
2058 ) => {
2059 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
2060
2061 const { data: myCustoms } = await query.graph({
2062 entity: "my_custom",
2063 fields: ["id", "name"],
2064 filters: {
2065 id: [
2066 "mc_01HWSVWR4D2XVPQ06DQ8X9K7AX",
2067 "mc_01HWSVWK3KYHKQEE6QGS2JC3FX",
2068 ],
2069 },
2070 })
2071
2072 res.json({ my_customs: myCustoms })
2073 }
2074 ```
2075
2076 Learn more in [this documentation](!docs!/learn/fundamentals/query#apply-filters).
2077
2078 ### Apply Pagination and Sort Records
2079
2080 To paginate and sort retrieved records:
2081
2082 ```ts highlights={[["21", "pagination"]]}
2083 import {
2084 MedusaRequest,
2085 MedusaResponse,
2086 } from "@medusajs/framework/http"
2087 import {
2088 ContainerRegistrationKeys,
2089 } from "@medusajs/framework/utils"
2090
2091 export const GET = async (
2092 req: MedusaRequest,
2093 res: MedusaResponse
2094 ) => {
2095 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
2096
2097 const {
2098 data: myCustoms,
2099 metadata: { count, take, skip } = {},
2100 } = await query.graph({
2101 entity: "my_custom",
2102 fields: ["id", "name"],
2103 pagination: {
2104 skip: 0,
2105 take: 10,
2106 order: {
2107 name: "DESC",
2108 },
2109 },
2110 })
2111
2112 res.json({
2113 my_customs: myCustoms,
2114 count,
2115 take,
2116 skip,
2117 })
2118 }
2119 ```
2120
2121 Learn more in [this documentation](!docs!/learn/fundamentals/query#sort-records).
2122
2123 ---
2124
2125 ## Workflows
2126
2127 A workflow is a series of queries and actions that complete a task.
2128
2129 A workflow allows you to track its execution's progress, provide roll-back logic for each step to mitigate data inconsistency when errors occur, automatically retry failing steps, and more.
2130
2131 ### Create a Workflow
2132
2133 To create a workflow:
2134
2135 1. Create the first step at `src/workflows/hello-world/steps/step-1.ts` with the following content:
2136
2137 ```ts title="src/workflows/hello-world/steps/step-1.ts"
2138 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2139
2140 export const step1 = createStep("step-1", async () => {
2141 return new StepResponse(`Hello from step one!`)
2142 })
2143 ```
2144
2145 2. Create the second step at `src/workflows/hello-world/steps/step-2.ts` with the following content:
2146
2147 ```ts title="src/workflows/hello-world/steps/step-2.ts"
2148 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2149
2150 type StepInput = {
2151 name: string
2152 }
2153
2154 export const step2 = createStep(
2155 "step-2",
2156 async ({ name }: StepInput) => {
2157 return new StepResponse(`Hello ${name} from step two!`)
2158 }
2159 )
2160 ```
2161
2162 3. Create the workflow at `src/workflows/hello-world/index.ts` with the following content:
2163
2164 ```ts title="src/workflows/hello-world/index.ts"
2165 import {
2166 createWorkflow,
2167 WorkflowResponse,
2168 } from "@medusajs/framework/workflows-sdk"
2169 import { step1 } from "./steps/step-1"
2170 import { step2 } from "./steps/step-2"
2171
2172 const myWorkflow = createWorkflow(
2173 "hello-world",
2174 function (input: WorkflowInput) {
2175 const str1 = step1()
2176 // to pass input
2177 const str2 = step2(input)
2178
2179 return new WorkflowResponse({
2180 message: str1,
2181 })
2182 }
2183 )
2184
2185 export default myWorkflow
2186 ```
2187
2188 Learn more in [this documentation](!docs!/learn/fundamentals/workflows).
2189
2190 ### Execute a Workflow
2191
2192 <CodeTabs group="resource-types">
2193 <CodeTab label="API Route" value="api-route">
2194
2195 ```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"], ["13"], ["14"], ["15"], ["16"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
2196 import type {
2197 MedusaRequest,
2198 MedusaResponse,
2199 } from "@medusajs/framework/http"
2200 import myWorkflow from "../../workflows/hello-world"
2201
2202 export async function GET(
2203 req: MedusaRequest,
2204 res: MedusaResponse
2205 ) {
2206 const { result } = await myWorkflow(req.scope)
2207 .run({
2208 input: {
2209 name: req.query.name as string,
2210 },
2211 })
2212
2213 res.send(result)
2214 }
2215 ```
2216
2217 </CodeTab>
2218 <CodeTab label="Subscriber" value="subscriber">
2219
2220 ```ts title="src/subscribers/customer-created.ts" highlights={[["20"], ["21"], ["22"], ["23"], ["24"], ["25"]]} collapsibleLines="1-9" expandButtonLabel="Show Imports"
2221 import {
2222 type SubscriberConfig,
2223 type SubscriberArgs,
2224 } from "@medusajs/framework"
2225 import myWorkflow from "../workflows/hello-world"
2226 import { Modules } from "@medusajs/framework/utils"
2227 import { IUserModuleService } from "@medusajs/framework/types"
2228
2229 export default async function handleCustomerCreate({
2230 event: { data },
2231 container,
2232 }: SubscriberArgs<{ id: string }>) {
2233 const userId = data.id
2234 const userModuleService: IUserModuleService = container.resolve(
2235 Modules.USER
2236 )
2237
2238 const user = await userModuleService.retrieveUser(userId)
2239
2240 const { result } = await myWorkflow(container)
2241 .run({
2242 input: {
2243 name: user.first_name,
2244 },
2245 })
2246
2247 console.log(result)
2248 }
2249
2250 export const config: SubscriberConfig = {
2251 event: "user.created",
2252 }
2253 ```
2254
2255 </CodeTab>
2256 <CodeTab label="Scheduled Job" value="scheduled-job">
2257
2258 ```ts title="src/jobs/message-daily.ts" highlights={[["7"], ["8"], ["9"], ["10"], ["11"], ["12"]]}
2259 import { MedusaContainer } from "@medusajs/framework/types"
2260 import myWorkflow from "../workflows/hello-world"
2261
2262 export default async function myCustomJob(
2263 container: MedusaContainer
2264 ) {
2265 const { result } = await myWorkflow(container)
2266 .run({
2267 input: {
2268 name: "John",
2269 },
2270 })
2271
2272 console.log(result.message)
2273 }
2274
2275 export const config = {
2276 name: "run-once-a-day",
2277 schedule: `0 0 * * *`,
2278 };
2279 ```
2280
2281 </CodeTab>
2282 </CodeTabs>
2283
2284 Learn more in [this documentation](!docs!/learn/fundamentals/workflows#3-execute-the-workflow).
2285
2286 ### Step with a Compensation Function
2287
2288 Pass a compensation function that undoes what a step did as a second parameter to `createStep`:
2289
2290 ```ts highlights={[["15"]]}
2291 import {
2292 createStep,
2293 StepResponse,
2294 } from "@medusajs/framework/workflows-sdk"
2295
2296 const step1 = createStep(
2297 "step-1",
2298 async () => {
2299 const message = `Hello from step one!`
2300
2301 console.log(message)
2302
2303 return new StepResponse(message)
2304 },
2305 async () => {
2306 console.log("Oops! Rolling back my changes...")
2307 }
2308 )
2309 ```
2310
2311 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/compensation-function).
2312
2313 ### Manipulate Variables in Workflow
2314
2315 To manipulate variables within a workflow's constructor function, use `transform` from the Workflows SDK:
2316
2317 ```ts highlights={[["14", "transform"]]}
2318 import {
2319 createWorkflow,
2320 WorkflowResponse,
2321 transform,
2322 } from "@medusajs/framework/workflows-sdk"
2323 // step imports...
2324
2325 const myWorkflow = createWorkflow(
2326 "hello-world",
2327 function (input) {
2328 const str1 = step1(input)
2329 const str2 = step2(input)
2330
2331 const str3 = transform(
2332 { str1, str2 },
2333 (data) => `${data.str1}${data.str2}`
2334 )
2335
2336 return new WorkflowResponse(str3)
2337 }
2338 )
2339 ```
2340
2341 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/variable-manipulation)
2342
2343 ### Using Conditions in Workflow
2344
2345 To perform steps or set a variable's value based on a condition, use `when-then` from the Workflows SDK:
2346
2347 ```ts highlights={[["14", "when"]]}
2348 import {
2349 createWorkflow,
2350 WorkflowResponse,
2351 when,
2352 } from "@medusajs/framework/workflows-sdk"
2353 // step imports...
2354
2355 const workflow = createWorkflow(
2356 "workflow",
2357 function (input: {
2358 is_active: boolean
2359 }) {
2360
2361 const result = when(
2362 input,
2363 (input) => {
2364 return input.is_active
2365 }
2366 ).then(() => {
2367 return isActiveStep()
2368 })
2369
2370 // executed without condition
2371 const anotherStepResult = anotherStep(result)
2372
2373 return new WorkflowResponse(
2374 anotherStepResult
2375 )
2376 }
2377 )
2378 ```
2379
2380 ### Run Workflow in Another
2381
2382 To run a workflow in another, use the workflow's `runAsStep` special method:
2383
2384 ```ts highlights={[["11", "runAsStep"]]}
2385 import {
2386 createWorkflow,
2387 } from "@medusajs/framework/workflows-sdk"
2388 import {
2389 createProductsWorkflow,
2390 } from "@medusajs/medusa/core-flows"
2391
2392 const workflow = createWorkflow(
2393 "hello-world",
2394 (input) => {
2395 const products = createProductsWorkflow.runAsStep({
2396 input: {
2397 products: [
2398 // ...
2399 ],
2400 },
2401 })
2402
2403 // ...
2404 }
2405 )
2406 ```
2407
2408 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/execute-another-workflow).
2409
2410 ### Consume a Workflow Hook
2411
2412 To consume a workflow hook, create a file under `src/workflows/hooks`:
2413
2414 ```ts title="src/workflows/hooks/product-created.ts"
2415 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
2416
2417 createProductsWorkflow.hooks.productsCreated(
2418 async ({ products, additional_data }, { container }) => {
2419 // TODO perform an action
2420 },
2421 async (dataFromStep, { container }) => {
2422 // undo the performed action
2423 }
2424 )
2425 ```
2426
2427 This executes a custom step at the hook's designated point in the workflow.
2428
2429 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/workflow-hooks).
2430
2431 ### Expose a Hook
2432
2433 To expose a hook in a workflow, pass it in the second parameter of the returned `WorkflowResponse`:
2434
2435 ```ts highlights={[["19", "hooks"]]}
2436 import {
2437 createStep,
2438 createHook,
2439 createWorkflow,
2440 WorkflowResponse,
2441 } from "@medusajs/framework/workflows-sdk"
2442 import { createProductStep } from "./steps/create-product"
2443
2444 export const myWorkflow = createWorkflow(
2445 "my-workflow",
2446 function (input) {
2447 const product = createProductStep(input)
2448 const productCreatedHook = createHook(
2449 "productCreated",
2450 { productId: product.id }
2451 )
2452
2453 return new WorkflowResponse(product, {
2454 hooks: [productCreatedHook],
2455 })
2456 }
2457 )
2458 ```
2459
2460 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/add-workflow-hook).
2461
2462 ### Retry Steps
2463
2464 To configure steps to retry in case of errors, pass the `maxRetries` step option:
2465
2466 ```ts highlights={[["10"]]}
2467 import {
2468 createStep,
2469 } from "@medusajs/framework/workflows-sdk"
2470
2471 export const step1 = createStep(
2472 {
2473 name: "step-1",
2474 maxRetries: 2,
2475 },
2476 async () => {
2477 console.log("Executing step 1")
2478
2479 throw new Error("Oops! Something happened.")
2480 }
2481 )
2482 ```
2483
2484 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/retry-failed-steps).
2485
2486 ### Run Steps in Parallel
2487
2488 If steps in a workflow don't depend on one another, run them in parallel using `parallel` from the Workflows SDK:
2489
2490 ```ts highlights={[["22", "parallelize"]]}
2491 import {
2492 createWorkflow,
2493 WorkflowResponse,
2494 parallelize,
2495 } from "@medusajs/framework/workflows-sdk"
2496 import {
2497 createProductStep,
2498 getProductStep,
2499 createPricesStep,
2500 attachProductToSalesChannelStep,
2501 } from "./steps"
2502
2503 interface WorkflowInput {
2504 title: string
2505 }
2506
2507 const myWorkflow = createWorkflow(
2508 "my-workflow",
2509 (input: WorkflowInput) => {
2510 const product = createProductStep(input)
2511
2512 const [prices, productSalesChannel] = parallelize(
2513 createPricesStep(product),
2514 attachProductToSalesChannelStep(product)
2515 )
2516
2517 const id = product.id
2518 const refetchedProduct = getProductStep(product.id)
2519
2520 return new WorkflowResponse(refetchedProduct)
2521 }
2522 )
2523 ```
2524
2525 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/parallel-steps).
2526
2527 ### Configure Workflow Timeout
2528
2529 To configure the timeout of a workflow, at which the workflow's status is changed, but its execution isn't stopped, use the `timeout` configuration:
2530
2531 ```ts highlights={[["10"]]}
2532 import {
2533 createStep,
2534 createWorkflow,
2535 WorkflowResponse,
2536 } from "@medusajs/framework/workflows-sdk"
2537 // step import...
2538
2539 const myWorkflow = createWorkflow({
2540 name: "hello-world",
2541 timeout: 2, // 2 seconds
2542 }, function () {
2543 const str1 = step1()
2544
2545 return new WorkflowResponse({
2546 message: str1,
2547 })
2548 })
2549
2550 export default myWorkflow
2551 ```
2552
2553 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/workflow-timeout).
2554
2555 ### Configure Step Timeout
2556
2557 To configure a step's timeout, at which its state changes but its execution isn't stopped, use the `timeout` property:
2558
2559 ```ts highlights={[["4"]]}
2560 const step1 = createStep(
2561 {
2562 name: "step-1",
2563 timeout: 2, // 2 seconds
2564 },
2565 async () => {
2566 // ...
2567 }
2568 )
2569 ```
2570
2571 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/workflow-timeout#configure-step-timeout).
2572
2573 ### Long-Running Workflow
2574
2575 A long-running workflow is a workflow that runs in the background. You can wait before executing some of its steps until another external or separate action occurs.
2576
2577 To create a long-running workflow, configure any of its steps to be `async` without returning any data:
2578
2579 ```ts highlights={[["4"]]}
2580 const step2 = createStep(
2581 {
2582 name: "step-2",
2583 async: true,
2584 },
2585 async () => {
2586 console.log("Waiting to be successful...")
2587 }
2588 )
2589 ```
2590
2591 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/long-running-workflow).
2592
2593 ### Change Step Status in Long-Running Workflow
2594
2595 To change a step's status:
2596
2597 1. Grab the workflow's transaction ID when you run it:
2598
2599 ```ts
2600 const { transaction } = await myLongRunningWorkflow(req.scope)
2601 .run()
2602 ```
2603
2604 2. In an API route, workflow, or other resource, change a step's status to successful using the [Workflow Engine Module](../infrastructure-modules/workflow-engine/page.mdx):
2605
2606 export const stepSuccessHighlights = [
2607 ["5", "setStepSuccess", "Change a step's status to success"],
2608 ["8", "transactionId", "Pass the workflow's transaction ID"],
2609 ["9", "stepId", "The ID of the step to change its status."],
2610 ["10", "workflowId", "The ID of the workflow that the step belongs to."]
2611 ]
2612
2613 ```ts highlights={stepSuccessHighlights}
2614 const workflowEngineService = container.resolve(
2615 Modules.WORKFLOW_ENGINE
2616 )
2617
2618 await workflowEngineService.setStepSuccess({
2619 idempotencyKey: {
2620 action: TransactionHandlerType.INVOKE,
2621 transactionId,
2622 stepId: "step-2",
2623 workflowId: "hello-world",
2624 },
2625 stepResponse: new StepResponse("Done!"),
2626 options: {
2627 container,
2628 },
2629 })
2630 ```
2631
2632 3. In an API route, workflow, or other resource, change a step's status to failure using the [Worfklow Engine Module](../infrastructure-modules/workflow-engine/page.mdx):
2633
2634 export const stepFailureHighlights = [
2635 ["5", "setStepFailure", "Change a step's status to failure"],
2636 ["8", "transactionId", "Pass the workflow's transaction ID"],
2637 ["9", "stepId", "The ID of the step to change its status."],
2638 ["10", "workflowId", "The ID of the workflow that the step belongs to."]
2639 ]
2640
2641 ```ts highlights={stepFailureHighlights}
2642 const workflowEngineService = container.resolve(
2643 Modules.WORKFLOW_ENGINE
2644 )
2645
2646 await workflowEngineService.setStepFailure({
2647 idempotencyKey: {
2648 action: TransactionHandlerType.INVOKE,
2649 transactionId,
2650 stepId: "step-2",
2651 workflowId: "hello-world",
2652 },
2653 stepResponse: new StepResponse("Failed!"),
2654 options: {
2655 container,
2656 },
2657 })
2658 ```
2659
2660 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/long-running-workflow).
2661
2662 ### Access Long-Running Workflow's Result
2663
2664 Use the Workflow Engine Module's `subscribe` and `unsubscribe` methods to access the status of a long-running workflow.
2665
2666 For example, in an API route:
2667
2668 ```ts highlights={[["18", "subscribe", "Subscribe to the workflow's status changes."]]}
2669 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2670 import myWorkflow from "../../../workflows/hello-world"
2671 import { Modules } from "@medusajs/framework/utils"
2672
2673 export async function GET(req: MedusaRequest, res: MedusaResponse) {
2674 const { transaction, result } = await myWorkflow(req.scope).run()
2675
2676 const workflowEngineService = req.scope.resolve(
2677 Modules.WORKFLOW_ENGINE
2678 )
2679
2680 const subscriptionOptions = {
2681 workflowId: "hello-world",
2682 transactionId: transaction.transactionId,
2683 subscriberId: "hello-world-subscriber",
2684 }
2685
2686 await workflowEngineService.subscribe({
2687 ...subscriptionOptions,
2688 subscriber: async (data) => {
2689 if (data.eventType === "onFinish") {
2690 console.log("Finished execution", data.result)
2691 // unsubscribe
2692 await workflowEngineService.unsubscribe({
2693 ...subscriptionOptions,
2694 subscriberOrId: subscriptionOptions.subscriberId,
2695 })
2696 } else if (data.eventType === "onStepFailure") {
2697 console.log("Workflow failed", data.step)
2698 }
2699 },
2700 })
2701
2702 res.send(result)
2703 }
2704 ```
2705
2706 Learn more in [this documentation](!docs!/learn/fundamentals/workflows/long-running-workflow#access-long-running-workflow-status-and-result).
2707
2708 ---
2709
2710 ## Subscribers
2711
2712 A subscriber is a function executed whenever the event it listens to is emitted.
2713
2714 ### Create a Subscriber
2715
2716 To create a subscriber that listens to the `product.created` event, create the file `src/subscribers/product-created.ts` with the following content:
2717
2718 ```ts title="src/subscribers/product-created.ts"
2719 import type {
2720 SubscriberArgs,
2721 SubscriberConfig,
2722 } from "@medusajs/framework"
2723
2724 export default async function productCreateHandler({
2725 event,
2726 }: SubscriberArgs<{ id: string }>) {
2727 const productId = event.data.id
2728 console.log(`The product ${productId} was created`)
2729 }
2730
2731 export const config: SubscriberConfig = {
2732 event: "product.created",
2733 }
2734 ```
2735
2736 Learn more in [this documentation](!docs!/learn/fundamentals/events-and-subscribers).
2737
2738 ### Resolve Resources in Subscriber
2739
2740 To resolve resources from the Medusa container in a subscriber, use the `container` property of its parameter:
2741
2742 ```ts highlights={[["6", "container"], ["8", "resolve", "Resolve the Product Module's main service."]]}
2743 import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
2744 import { Modules } from "@medusajs/framework/utils"
2745
2746 export default async function productCreateHandler({
2747 event: { data },
2748 container,
2749 }: SubscriberArgs<{ id: string }>) {
2750 const productModuleService = container.resolve(Modules.PRODUCT)
2751
2752 const productId = data.id
2753
2754 const product = await productModuleService.retrieveProduct(
2755 productId
2756 )
2757
2758 console.log(`The product ${product.title} was created`)
2759 }
2760
2761 export const config: SubscriberConfig = {
2762 event: `product.created`,
2763 }
2764 ```
2765
2766 Learn more in [this documentation](!docs!/learn/fundamentals/events-and-subscribers#resolve-resources).
2767
2768 ### Send a Notification to Reset Password
2769
2770 To send a notification, such as an email when a user requests to reset their password, create a subscriber at `src/subscribers/handle-reset.ts` with the following content:
2771
2772 ```ts title="src/subscribers/handle-reset.ts"
2773 import {
2774 SubscriberArgs,
2775 type SubscriberConfig,
2776 } from "@medusajs/medusa"
2777 import { Modules } from "@medusajs/framework/utils"
2778
2779 export default async function resetPasswordTokenHandler({
2780 event: { data: {
2781 entity_id: email,
2782 token,
2783 actor_type,
2784 } },
2785 container,
2786 }: SubscriberArgs<{ entity_id: string, token: string, actor_type: string }>) {
2787 const notificationModuleService = container.resolve(
2788 Modules.NOTIFICATION
2789 )
2790
2791 const urlPrefix = actor_type === "customer" ?
2792 "https://storefront.com" :
2793 "https://admin.com"
2794
2795 await notificationModuleService.createNotifications({
2796 to: email,
2797 channel: "email",
2798 template: "reset-password-template",
2799 data: {
2800 // a URL to a frontend application
2801 url: `${urlPrefix}/reset-password?token=${token}&email=${email}`,
2802 },
2803 })
2804 }
2805
2806 export const config: SubscriberConfig = {
2807 event: "auth.password_reset",
2808 }
2809 ```
2810
2811 Learn more in [this documentation](../commerce-modules/auth/reset-password/page.mdx).
2812
2813 ### Execute a Workflow in a Subscriber
2814
2815 To execute a workflow in a subscriber:
2816
2817 ```ts
2818 import {
2819 type SubscriberConfig,
2820 type SubscriberArgs,
2821 } from "@medusajs/framework"
2822 import myWorkflow from "../workflows/hello-world"
2823 import { Modules } from "@medusajs/framework/utils"
2824
2825 export default async function handleCustomerCreate({
2826 event: { data },
2827 container,
2828 }: SubscriberArgs<{ id: string }>) {
2829 const userId = data.id
2830 const userModuleService = container.resolve(
2831 Modules.USER
2832 )
2833
2834 const user = await userModuleService.retrieveUser(userId)
2835
2836 const { result } = await myWorkflow(container)
2837 .run({
2838 input: {
2839 name: user.first_name,
2840 },
2841 })
2842
2843 console.log(result)
2844 }
2845
2846 export const config: SubscriberConfig = {
2847 event: "user.created",
2848 }
2849 ```
2850
2851 Learn more in [this documentation](!docs!/learn/fundamentals/workflows#3-execute-the-workflow)
2852
2853 ---
2854
2855 ## Scheduled Jobs
2856
2857 A scheduled job is a function executed at a specified interval of time in the background of your Medusa application.
2858
2859 ### Create a Scheduled Job
2860
2861 To create a scheduled job, create the file `src/jobs/hello-world.ts` with the following content:
2862
2863 ```ts title="src/jobs/hello-world.ts"
2864 // the scheduled-job function
2865 export default async function () {
2866 console.log("Time to say hello world!")
2867 }
2868
2869 // the job's configurations
2870 export const config = {
2871 name: "every-minute-message",
2872 // execute every minute
2873 schedule: "* * * * *",
2874 }
2875 ```
2876
2877 Learn more in [this documentation](!docs!/learn/fundamentals/scheduled-jobs).
2878
2879 ### Resolve Resources in Scheduled Job
2880
2881 To resolve resources in a scheduled job, use the `container` accepted as a first parameter:
2882
2883 ```ts highlights={[["5", "container"], ["7", "resolve", "Resolve the Product Module's main service."]]}
2884 import { MedusaContainer } from "@medusajs/framework/types"
2885 import { Modules } from "@medusajs/framework/utils"
2886
2887 export default async function myCustomJob(
2888 container: MedusaContainer
2889 ) {
2890 const productModuleService = container.resolve(Modules.PRODUCT)
2891
2892 const [, count] = await productModuleService.listAndCountProducts()
2893
2894 console.log(
2895 `Time to check products! You have ${count} product(s)`
2896 )
2897 }
2898
2899 export const config = {
2900 name: "every-minute-message",
2901 // execute every minute
2902 schedule: "* * * * *",
2903 }
2904 ```
2905
2906 Learn more in [this documentation](!docs!/learn/fundamentals/scheduled-jobs#resolve-resources)
2907
2908 ### Specify a Job's Execution Number
2909
2910 To limit the scheduled job's execution to a number of times during the Medusa application's runtime, use the `numberOfExecutions` configuration:
2911
2912 ```ts highlights={[["9", "numberOfExecutions"]]}
2913 export default async function myCustomJob() {
2914 console.log("I'll be executed three times only.")
2915 }
2916
2917 export const config = {
2918 name: "hello-world",
2919 // execute every minute
2920 schedule: "* * * * *",
2921 numberOfExecutions: 3,
2922 }
2923 ```
2924
2925 Learn more in [this documentation](!docs!/learn/fundamentals/scheduled-jobs/execution-number).
2926
2927 ### Execute a Workflow in a Scheduled Job
2928
2929 To execute a workflow in a scheduled job:
2930
2931 ```ts
2932 import { MedusaContainer } from "@medusajs/framework/types"
2933 import myWorkflow from "../workflows/hello-world"
2934
2935 export default async function myCustomJob(
2936 container: MedusaContainer
2937 ) {
2938 const { result } = await myWorkflow(container)
2939 .run({
2940 input: {
2941 name: "John",
2942 },
2943 })
2944
2945 console.log(result.message)
2946 }
2947
2948 export const config = {
2949 name: "run-once-a-day",
2950 schedule: `0 0 * * *`,
2951 }
2952 ```
2953
2954 Learn more in [this documentation](!docs!/learn/fundamentals/workflows#3-execute-the-workflow)
2955
2956 ---
2957
2958 ## Loaders
2959
2960 A loader is a function defined in a module that's executed when the Medusa application starts.
2961
2962 ### Create a Loader
2963
2964 To create a loader, add it to a module's `loaders` directory.
2965
2966 For example, create the file `src/modules/hello/loaders/hello-world.ts` with the following content:
2967
2968 ```ts title="src/modules/hello/loaders/hello-world.ts"
2969 export default async function helloWorldLoader() {
2970 console.log(
2971 "[HELLO MODULE] Just started the Medusa application!"
2972 )
2973 }
2974 ```
2975
2976 Learn more in [this documentation](!docs!/learn/fundamentals/modules/loaders).
2977
2978 ### Resolve Resources in Loader
2979
2980 To resolve resources in a loader, use the `container` property of its first parameter:
2981
2982 ```ts highlights={[["9", "container"], ["11", "resolve", "Resolve the Logger from the module's container."]]}
2983 import {
2984 LoaderOptions,
2985 } from "@medusajs/framework/types"
2986 import {
2987 ContainerRegistrationKeys,
2988 } from "@medusajs/framework/utils"
2989
2990 export default async function helloWorldLoader({
2991 container,
2992 }: LoaderOptions) {
2993 const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
2994
2995 logger.info("[helloWorldLoader]: Hello, World!")
2996 }
2997 ```
2998
2999 Learn more in [this documentation](!docs!/learn/fundamentals/modules/container).
3000
3001 ### Access Module Options
3002
3003 To access a module's options in its loader, use the `options` property of its first parameter:
3004
3005 ```ts highlights={[["11", "options"]]}
3006 import {
3007 LoaderOptions,
3008 } from "@medusajs/framework/types"
3009
3010 // recommended to define type in another file
3011 type ModuleOptions = {
3012 apiKey?: boolean
3013 }
3014
3015 export default async function helloWorldLoader({
3016 options,
3017 }: LoaderOptions<ModuleOptions>) {
3018
3019 console.log(
3020 "[HELLO MODULE] Just started the Medusa application!",
3021 options
3022 )
3023 }
3024 ```
3025
3026 Learn more in [this documentation](!docs!/learn/fundamentals/modules/options).
3027
3028 ### Register Resources in the Module's Container
3029
3030 To register a resource in the Module's container using a loader, use the `container`'s `registerAdd` method:
3031
3032 ```ts highlights={[["9", "registerAdd"]]}
3033 import {
3034 LoaderOptions,
3035 } from "@medusajs/framework/types"
3036 import { asValue } from "@medusajs/framework/awilix"
3037
3038 export default async function helloWorldLoader({
3039 container,
3040 }: LoaderOptions) {
3041 container.registerAdd(
3042 "custom_data",
3043 asValue({
3044 test: true,
3045 })
3046 )
3047 }
3048 ```
3049
3050 Where the first parameter of `registerAdd` is the name to register the resource under, and the second parameter is the resource to register.
3051
3052 ---
3053
3054 ## Admin Customizations
3055
3056 You can customize the Medusa Admin to inject widgets in existing pages, or create new pages using UI routes.
3057
3058 <Note>
3059
3060 For a list of components to use in the admin dashboard, refer to [this documentation](../admin-components/page.mdx).
3061
3062 </Note>
3063
3064 ### Create Widget
3065
3066 A widget is a React component that can be injected into an existing page in the admin dashboard.
3067
3068 To create a widget in the admin dashboard, create the file `src/admin/widgets/products-widget.tsx` with the following content:
3069
3070 ```tsx title="src/admin/widgets/products-widget.tsx"
3071 import { defineWidgetConfig } from "@medusajs/admin-sdk"
3072 import { Container, Heading } from "@medusajs/ui"
3073
3074 const ProductWidget = () => {
3075 return (
3076 <Container className="divide-y p-0">
3077 <div className="flex items-center justify-between px-6 py-4">
3078 <Heading level="h2">Product Widget</Heading>
3079 </div>
3080 </Container>
3081 )
3082 }
3083
3084 export const config = defineWidgetConfig({
3085 zone: "product.list",
3086 })
3087
3088 export default ProductWidget
3089 ```
3090
3091 Learn more about widgets in [this documentation](!docs!/learn/fundamentals/admin/widgets).
3092
3093 ### Receive Details Props in Widgets
3094
3095 Widgets created in a details page, such as widgets in the `product.details` injection zone, receive a prop of the data of the details page (for example, the product):
3096
3097 ```tsx highlights={[["10", "data"]]}
3098 import { defineWidgetConfig } from "@medusajs/admin-sdk"
3099 import { Container, Heading } from "@medusajs/ui"
3100 import {
3101 DetailWidgetProps,
3102 AdminProduct,
3103 } from "@medusajs/framework/types"
3104
3105 // The widget
3106 const ProductWidget = ({
3107 data,
3108 }: DetailWidgetProps<AdminProduct>) => {
3109 return (
3110 <Container className="divide-y p-0">
3111 <div className="flex items-center justify-between px-6 py-4">
3112 <Heading level="h2">
3113 Product Widget {data.title}
3114 </Heading>
3115 </div>
3116 </Container>
3117 )
3118 }
3119
3120 // The widget's configurations
3121 export const config = defineWidgetConfig({
3122 zone: "product.details",
3123 })
3124
3125 export default ProductWidget
3126 ```
3127
3128 Learn more in [this documentation](!docs!/learn/fundamentals/admin/widgets#detail-widget-props).
3129
3130 ### Create a UI Route
3131
3132 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.
3133
3134 To create a UI route in the admin dashboard, create the file `src/admin/routes/custom/page.tsx` with the following content:
3135
3136 ```tsx title="src/admin/routes/custom/page.tsx"
3137 import { defineRouteConfig } from "@medusajs/admin-sdk"
3138 import { ChatBubbleLeftRight } from "@medusajs/icons"
3139 import { Container, Heading } from "@medusajs/ui"
3140
3141 const CustomPage = () => {
3142 return (
3143 <Container className="divide-y p-0">
3144 <div className="flex items-center justify-between px-6 py-4">
3145 <Heading level="h2">This is my custom route</Heading>
3146 </div>
3147 </Container>
3148 )
3149 }
3150
3151 export const config = defineRouteConfig({
3152 label: "Custom Route",
3153 icon: ChatBubbleLeftRight,
3154 })
3155
3156 export default CustomPage
3157 ```
3158
3159 This adds a new page at `localhost:9000/app/custom`.
3160
3161 Learn more in [this documentation](!docs!/learn/fundamentals/admin/ui-routes).
3162
3163 ### Create Settings Page
3164
3165 To create a settings page, create a UI route under the `src/admin/routes/settings` directory.
3166
3167 For example, create the file `src/admin/routes/settings/custom/page.tsx` with the following content:
3168
3169 ```tsx title="src/admin/routes/settings/custom/page.tsx"
3170 import { defineRouteConfig } from "@medusajs/admin-sdk"
3171 import { Container, Heading } from "@medusajs/ui"
3172
3173 const CustomSettingPage = () => {
3174 return (
3175 <Container className="divide-y p-0">
3176 <div className="flex items-center justify-between px-6 py-4">
3177 <Heading level="h1">Custom Setting Page</Heading>
3178 </div>
3179 </Container>
3180 )
3181 }
3182
3183 export const config = defineRouteConfig({
3184 label: "Custom",
3185 })
3186
3187 export default CustomSettingPage
3188 ```
3189
3190 This adds a setting page at `localhost:9000/app/settings/custom`.
3191
3192 Learn more in [this documentation](!docs!/learn/fundamentals/admin/ui-routes#create-settings-page)
3193
3194 ### Accept Path Parameters in UI Routes
3195
3196 To accept a path parameter in a UI route, name one of the directories in its path in the format `[param]`.
3197
3198 For example, create the file `src/admin/routes/custom/[id]/page.tsx` with the following content:
3199
3200 ```tsx title="src/admin/routes/custom/[id]/page.tsx"
3201 import { useParams } from "react-router-dom"
3202 import { Container } from "@medusajs/ui"
3203
3204 const CustomPage = () => {
3205 const { id } = useParams()
3206
3207 return (
3208 <Container className="divide-y p-0">
3209 <div className="flex items-center justify-between px-6 py-4">
3210 <Heading level="h1">Passed ID: {id}</Heading>
3211 </div>
3212 </Container>
3213 )
3214 }
3215
3216 export default CustomPage
3217 ```
3218
3219 This creates a UI route at `localhost:9000/app/custom/:id`, where `:id` is a path parameter.
3220
3221 Learn more in [this documentation](!docs!/learn/fundamentals/admin/ui-routes#path-parameters)
3222
3223 ### Send Request to API Route
3224
3225 To send a request to custom API routes from the admin dashboard, use the Fetch API.
3226
3227 For example:
3228
3229 ```tsx
3230 import { defineWidgetConfig } from "@medusajs/admin-sdk"
3231 import { Container } from "@medusajs/ui"
3232 import { useEffect, useState } from "react"
3233
3234 const ProductWidget = () => {
3235 const [productsCount, setProductsCount] = useState(0)
3236 const [loading, setLoading] = useState(true)
3237
3238 useEffect(() => {
3239 if (!loading) {
3240 return
3241 }
3242
3243 fetch(`/admin/products`, {
3244 credentials: "include",
3245 })
3246 .then((res) => res.json())
3247 .then(({ count }) => {
3248 setProductsCount(count)
3249 setLoading(false)
3250 })
3251 }, [loading])
3252
3253 return (
3254 <Container className="divide-y p-0">
3255 {loading && <span>Loading...</span>}
3256 {!loading && <span>You have {productsCount} Product(s).</span>}
3257 </Container>
3258 )
3259 }
3260
3261 export const config = defineWidgetConfig({
3262 zone: "product.list",
3263 })
3264
3265 export default ProductWidget
3266 ```
3267
3268 Learn more in [this documentation](!docs!/learn/fundamentals/admin/tips#send-requests-to-api-routes)
3269
3270 ### Add Link to Another Page
3271
3272 To add a link to another page in a UI route or a widget, use `react-router-dom`'s `Link` component:
3273
3274 ```tsx
3275 import { defineWidgetConfig } from "@medusajs/admin-sdk"
3276 import { Container } from "@medusajs/ui"
3277 import { Link } from "react-router-dom"
3278
3279 // The widget
3280 const ProductWidget = () => {
3281 return (
3282 <Container className="divide-y p-0">
3283 <Link to={"/orders"}>View Orders</Link>
3284 </Container>
3285 )
3286 }
3287
3288 // The widget's configurations
3289 export const config = defineWidgetConfig({
3290 zone: "product.details",
3291 })
3292
3293 export default ProductWidget
3294 ```
3295
3296 Learn more in [this documentation](!docs!/learn/fundamentals/admin/tips#routing-functionalities).
3297
3298 ---
3299
3300 ## Integration Tests
3301
3302 Medusa provides a `@medusajs/test-utils` package with utility tools to create integration tests for your custom API routes, modules, or other Medusa customizations.
3303
3304 <Note>
3305
3306 For details on setting up your project for integration tests, refer to [this documentation](!docs!/learn/debugging-and-testing/testing-tools).
3307
3308 </Note>
3309
3310 ### Test Custom API Route
3311
3312 To create a test for a custom API route, create the file `integration-tests/http/custom-routes.spec.ts` with the following content:
3313
3314 ```ts title="integration-tests/http/custom-routes.spec.ts"
3315 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
3316
3317 medusaIntegrationTestRunner({
3318 testSuite: ({ api, getContainer }) => {
3319 describe("Custom endpoints", () => {
3320 describe("GET /custom", () => {
3321 it("returns correct message", async () => {
3322 const response = await api.get(
3323 `/custom`
3324 )
3325
3326 expect(response.status).toEqual(200)
3327 expect(response.data).toHaveProperty("message")
3328 expect(response.data.message).toEqual("Hello, World!")
3329 })
3330 })
3331 })
3332 },
3333 })
3334 ```
3335
3336 Then, run the test with the following command:
3337
3338 ```bash npm2yarn
3339 npm run test:integration
3340 ```
3341
3342 Learn more in [this documentation](!docs!/learn/debugging-and-testing/testing-tools/integration-tests/api-routes).
3343
3344 ### Test Workflow
3345
3346 To create a test for a workflow, create the file `integration-tests/http/workflow.spec.ts` with the following content:
3347
3348 ```ts title="integration-tests/http/workflow.spec.ts"
3349 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
3350 import { helloWorldWorkflow } from "../../src/workflows/hello-world"
3351
3352 medusaIntegrationTestRunner({
3353 testSuite: ({ getContainer }) => {
3354 describe("Test hello-world workflow", () => {
3355 it("returns message", async () => {
3356 const { result } = await helloWorldWorkflow(getContainer())
3357 .run()
3358
3359 expect(result).toEqual("Hello, World!")
3360 })
3361 })
3362 },
3363 })
3364 ```
3365
3366 Then, run the test with the following command:
3367
3368 ```bash npm2yarn
3369 npm run test:integration
3370 ```
3371
3372 Learn more in [this documentation](!docs!/learn/debugging-and-testing/testing-tools/integration-tests/workflows).
3373
3374 ### Test Module's Service
3375
3376 To create a test for a module's service, create the test under the `__tests__` directory of the module.
3377
3378 For example, create the file `src/modules/blog/__tests__/service.spec.ts` with the following content:
3379
3380 ```ts title="src/modules/blog/__tests__/service.spec.ts"
3381 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
3382 import { BLOG_MODULE } from ".."
3383 import BlogModuleService from "../service"
3384 import Post from "../models/post"
3385
3386 moduleIntegrationTestRunner<BlogModuleService>({
3387 moduleName: BLOG_MODULE,
3388 moduleModels: [Post],
3389 resolve: "./modules/blog",
3390 testSuite: ({ service }) => {
3391 describe("BlogModuleService", () => {
3392 it("says hello world", () => {
3393 const message = service.getMessage()
3394
3395 expect(message).toEqual("Hello, World!")
3396 })
3397 })
3398 },
3399 })
3400 ```
3401
3402 Then, run the test with the following command:
3403
3404 ```bash npm2yarn
3405 npm run test:modules
3406 ```
3407
3408 ---
3409
3410 ## Commerce Modules
3411
3412 Medusa provides all its commerce features as separate Commerce Modules, such as the Product or Order modules.
3413
3414 <Note>
3415
3416 Refer to the [Commerce Modules](../commerce-modules/page.mdx) documentation for concepts and reference of every module's main service.
3417
3418 </Note>
3419
3420 ### Create an Actor Type to Authenticate
3421
3422 To create an actor type that can authenticate to the Medusa application, such as a `manager`:
3423
3424 1. Create the data model in a module:
3425
3426 ```ts
3427 import { model } from "@medusajs/framework/utils"
3428
3429 const Manager = model.define("manager", {
3430 id: model.id().primaryKey(),
3431 firstName: model.text(),
3432 lastName: model.text(),
3433 email: model.text(),
3434 })
3435
3436 export default Manager
3437 ```
3438
3439 2. Use the `setAuthAppMetadataStep` as a step in a workflow that creates a manager:
3440
3441 ```ts
3442 import {
3443 createWorkflow,
3444 WorkflowResponse,
3445 } from "@medusajs/framework/workflows-sdk"
3446 import {
3447 setAuthAppMetadataStep,
3448 } from "@medusajs/medusa/core-flows"
3449 // other imports...
3450
3451 const createManagerWorkflow = createWorkflow(
3452 "create-manager",
3453 function (input: CreateManagerWorkflowInput) {
3454 const manager = createManagerStep({
3455 manager: input.manager,
3456 })
3457
3458 setAuthAppMetadataStep({
3459 authIdentityId: input.authIdentityId,
3460 actorType: "manager",
3461 value: manager.id,
3462 })
3463
3464 return new WorkflowResponse(manager)
3465 }
3466 )
3467 ```
3468
3469 3. Use the workflow in an API route that creates a user (manager) of the actor type:
3470
3471 ```ts
3472 import type {
3473 AuthenticatedMedusaRequest,
3474 MedusaResponse,
3475 } from "@medusajs/framework/http"
3476 import { MedusaError } from "@medusajs/framework/utils"
3477 import createManagerWorkflow from "../../workflows/create-manager"
3478
3479 type RequestBody = {
3480 first_name: string
3481 last_name: string
3482 email: string
3483 }
3484
3485 export async function POST(
3486 req: AuthenticatedMedusaRequest<RequestBody>,
3487 res: MedusaResponse
3488 ) {
3489 // If `actor_id` is present, the request carries
3490 // authentication for an existing manager
3491 if (req.auth_context.actor_id) {
3492 throw new MedusaError(
3493 MedusaError.Types.INVALID_DATA,
3494 "Request already authenticated as a manager."
3495 )
3496 }
3497
3498 const { result } = await createManagerWorkflow(req.scope)
3499 .run({
3500 input: {
3501 manager: req.body,
3502 authIdentityId: req.auth_context.auth_identity_id,
3503 },
3504 })
3505
3506 res.status(200).json({ manager: result })
3507 }
3508 ```
3509
3510 4. Apply the `authenticate` middleware on the new route in `src/api/middlewares.ts`:
3511
3512 ```ts title="src/api/middlewares.ts"
3513 import {
3514 defineMiddlewares,
3515 authenticate,
3516 } from "@medusajs/framework/http"
3517
3518 export default defineMiddlewares({
3519 routes: [
3520 {
3521 matcher: "/manager",
3522 method: "POST",
3523 middlewares: [
3524 authenticate("manager", ["session", "bearer"], {
3525 allowUnregistered: true,
3526 }),
3527 ],
3528 },
3529 {
3530 matcher: "/manager/me*",
3531 middlewares: [
3532 authenticate("manager", ["session", "bearer"]),
3533 ],
3534 },
3535 ],
3536 })
3537 ```
3538
3539 Now, manager users can use the `/manager` API route to register, and all routes starting with `/manager/me` are only accessible by authenticated managers.
3540
3541 Find an elaborate example and learn more in [this documentation](../commerce-modules/auth/create-actor-type/page.mdx).
3542
3543 ### Apply Promotion on Cart Items and Shipping
3544
3545 To apply a promotion on a cart's items and shipping methods using the [Cart](../commerce-modules/cart/page.mdx) and [Promotion](../commerce-modules/promotion/page.mdx) modules:
3546
3547 ```ts
3548 import {
3549 ComputeActionAdjustmentLine,
3550 ComputeActionItemLine,
3551 ComputeActionShippingLine,
3552 AddItemAdjustmentAction,
3553 AddShippingMethodAdjustment,
3554 // ...
3555 } from "@medusajs/framework/types"
3556
3557 // retrieve the cart
3558 const cart = await cartModuleService.retrieveCart("cart_123", {
3559 relations: [
3560 "items.adjustments",
3561 "shipping_methods.adjustments",
3562 ],
3563 })
3564
3565 // retrieve line item adjustments
3566 const lineItemAdjustments: ComputeActionItemLine[] = []
3567 cart.items.forEach((item) => {
3568 const filteredAdjustments = item.adjustments?.filter(
3569 (adjustment) => adjustment.code !== undefined
3570 ) as unknown as ComputeActionAdjustmentLine[]
3571 if (filteredAdjustments.length) {
3572 lineItemAdjustments.push({
3573 ...item,
3574 adjustments: filteredAdjustments,
3575 })
3576 }
3577 })
3578
3579 // retrieve shipping method adjustments
3580 const shippingMethodAdjustments: ComputeActionShippingLine[] =
3581 []
3582 cart.shipping_methods.forEach((shippingMethod) => {
3583 const filteredAdjustments =
3584 shippingMethod.adjustments?.filter(
3585 (adjustment) => adjustment.code !== undefined
3586 ) as unknown as ComputeActionAdjustmentLine[]
3587 if (filteredAdjustments.length) {
3588 shippingMethodAdjustments.push({
3589 ...shippingMethod,
3590 adjustments: filteredAdjustments,
3591 })
3592 }
3593 })
3594
3595 // compute actions
3596 const actions = await promotionModuleService.computeActions(
3597 ["promo_123"],
3598 {
3599 items: lineItemAdjustments,
3600 shipping_methods: shippingMethodAdjustments,
3601 }
3602 )
3603
3604 // set the adjustments on the line item
3605 await cartModuleService.setLineItemAdjustments(
3606 cart.id,
3607 actions.filter(
3608 (action) => action.action === "addItemAdjustment"
3609 ) as AddItemAdjustmentAction[]
3610 )
3611
3612 // set the adjustments on the shipping method
3613 await cartModuleService.setShippingMethodAdjustments(
3614 cart.id,
3615 actions.filter(
3616 (action) =>
3617 action.action === "addShippingMethodAdjustment"
3618 ) as AddShippingMethodAdjustment[]
3619 )
3620 ```
3621
3622 Learn more in [this documentation](../commerce-modules/cart/tax-lines/page.mdx).
3623
3624 ### Retrieve Tax Lines of a Cart's Items and Shipping
3625
3626 To retrieve the tax lines of a cart's items and shipping methods using the [Cart](../commerce-modules/cart/page.mdx) and [Tax](../commerce-modules/tax/page.mdx) modules:
3627
3628 ```ts
3629 // retrieve the cart
3630 const cart = await cartModuleService.retrieveCart("cart_123", {
3631 relations: [
3632 "items.tax_lines",
3633 "shipping_methods.tax_lines",
3634 "shipping_address",
3635 ],
3636 })
3637
3638 // retrieve the tax lines
3639 const taxLines = await taxModuleService.getTaxLines(
3640 [
3641 ...(cart.items as TaxableItemDTO[]),
3642 ...(cart.shipping_methods as TaxableShippingDTO[]),
3643 ],
3644 {
3645 address: {
3646 ...cart.shipping_address,
3647 country_code:
3648 cart.shipping_address.country_code || "us",
3649 },
3650 }
3651 )
3652
3653 // set line item tax lines
3654 await cartModuleService.setLineItemTaxLines(
3655 cart.id,
3656 taxLines.filter((line) => "line_item_id" in line)
3657 )
3658
3659 // set shipping method tax lines
3660 await cartModuleService.setLineItemTaxLines(
3661 cart.id,
3662 taxLines.filter((line) => "shipping_line_id" in line)
3663 )
3664 ```
3665
3666 Learn more in [this documentation](../commerce-modules/cart/tax-lines/page.mdx)
3667
3668 ### Apply Promotion on an Order's Items and Shipping
3669
3670 To apply a promotion on an order's items and shipping methods using the [Order](../commerce-modules/order/page.mdx) and [Promotion](../commerce-modules/promotion/page.mdx) modules:
3671
3672 ```ts
3673 import {
3674 ComputeActionAdjustmentLine,
3675 ComputeActionItemLine,
3676 ComputeActionShippingLine,
3677 AddItemAdjustmentAction,
3678 AddShippingMethodAdjustment,
3679 // ...
3680 } from "@medusajs/framework/types"
3681
3682 // ...
3683
3684 // retrieve the order
3685 const order = await orderModuleService.retrieveOrder("ord_123", {
3686 relations: [
3687 "items.item.adjustments",
3688 "shipping_methods.shipping_method.adjustments",
3689 ],
3690 })
3691 // retrieve the line item adjustments
3692 const lineItemAdjustments: ComputeActionItemLine[] = []
3693 order.items.forEach((item) => {
3694 const filteredAdjustments = item.adjustments?.filter(
3695 (adjustment) => adjustment.code !== undefined
3696 ) as unknown as ComputeActionAdjustmentLine[]
3697 if (filteredAdjustments.length) {
3698 lineItemAdjustments.push({
3699 ...item,
3700 ...item.detail,
3701 adjustments: filteredAdjustments,
3702 })
3703 }
3704 })
3705
3706 //retrieve shipping method adjustments
3707 const shippingMethodAdjustments: ComputeActionShippingLine[] =
3708 []
3709 order.shipping_methods.forEach((shippingMethod) => {
3710 const filteredAdjustments =
3711 shippingMethod.adjustments?.filter(
3712 (adjustment) => adjustment.code !== undefined
3713 ) as unknown as ComputeActionAdjustmentLine[]
3714 if (filteredAdjustments.length) {
3715 shippingMethodAdjustments.push({
3716 ...shippingMethod,
3717 adjustments: filteredAdjustments,
3718 })
3719 }
3720 })
3721
3722 // compute actions
3723 const actions = await promotionModuleService.computeActions(
3724 ["promo_123"],
3725 {
3726 items: lineItemAdjustments,
3727 shipping_methods: shippingMethodAdjustments,
3728 // TODO infer from cart or region
3729 currency_code: "usd",
3730 }
3731 )
3732
3733 // set the adjustments on the line items
3734 await orderModuleService.setOrderLineItemAdjustments(
3735 order.id,
3736 actions.filter(
3737 (action) => action.action === "addItemAdjustment"
3738 ) as AddItemAdjustmentAction[]
3739 )
3740
3741 // set the adjustments on the shipping methods
3742 await orderModuleService.setOrderShippingMethodAdjustments(
3743 order.id,
3744 actions.filter(
3745 (action) =>
3746 action.action === "addShippingMethodAdjustment"
3747 ) as AddShippingMethodAdjustment[]
3748 )
3749 ```
3750
3751 Learn more in [this documentation](../commerce-modules/order/promotion-adjustments/page.mdx)
3752
3753 ### Accept Payment using Module
3754
3755 To accept payment using the Payment Module's main service:
3756
3757 1. Create a payment collection and link it to the cart:
3758
3759 ```ts
3760 import {
3761 ContainerRegistrationKeys,
3762 Modules,
3763 } from "@medusajs/framework/utils"
3764
3765 // ...
3766
3767 const paymentCollection =
3768 await paymentModuleService.createPaymentCollections({
3769 region_id: "reg_123",
3770 currency_code: "usd",
3771 amount: 50,
3772 })
3773
3774 // resolve Link
3775 const link = container.resolve(
3776 ContainerRegistrationKeys.LINK
3777 )
3778
3779 // create a link between the cart and payment collection
3780 link.create({
3781 [Modules.CART]: {
3782 cart_id: "cart_123",
3783 },
3784 [Modules.PAYMENT]: {
3785 payment_collection_id: paymentCollection.id,
3786 },
3787 })
3788 ```
3789
3790 2. Create a payment session in the collection:
3791
3792 ```ts
3793 const paymentSession =
3794 await paymentModuleService.createPaymentSession(
3795 paymentCollection.id,
3796 {
3797 provider_id: "stripe",
3798 currency_code: "usd",
3799 amount: 50,
3800 data: {
3801 // any necessary data for the
3802 // payment provider
3803 },
3804 }
3805 )
3806 ```
3807
3808 3. Authorize the payment session:
3809
3810 ```ts
3811 const payment =
3812 await paymentModuleService.authorizePaymentSession(
3813 paymentSession.id,
3814 {}
3815 )
3816 ```
3817
3818 Learn more in [this documentation](../commerce-modules/payment/payment-flow/page.mdx).
3819
3820 ### Get Variant's Prices for Region and Currency
3821
3822 To get prices of a product variant for a region and currency using [Query](!docs!/learn/fundamentals/query):
3823
3824 ```ts
3825 import { QueryContext } from "@medusajs/framework/utils"
3826
3827 // ...
3828
3829 const { data: products } = await query.graph({
3830 entity: "product",
3831 fields: [
3832 "*",
3833 "variants.*",
3834 "variants.calculated_price.*",
3835 ],
3836 filters: {
3837 id: "prod_123",
3838 },
3839 context: {
3840 variants: {
3841 calculated_price: QueryContext({
3842 region_id: "reg_01J3MRPDNXXXDSCC76Y6YCZARS",
3843 currency_code: "eur",
3844 }),
3845 },
3846 },
3847 })
3848 ```
3849
3850 Learn more in [this documentation](../commerce-modules/product/guides/price/page.mdx#retrieve-calculated-price-for-a-context).
3851
3852 ### Get All Variant's Prices
3853
3854 To get all prices of a product variant using [Query](!docs!/learn/fundamentals/query):
3855
3856 ```ts
3857 const { data: products } = await query.graph({
3858 entity: "product",
3859 fields: [
3860 "*",
3861 "variants.*",
3862 "variants.prices.*",
3863 ],
3864 filters: {
3865 id: [
3866 "prod_123",
3867 ],
3868 },
3869 })
3870 ```
3871
3872 Learn more in [this documentation](../commerce-modules/product/guides/price/page.mdx).
3873
3874 ### Get Variant Prices with Taxes
3875
3876 To get a variant's prices with taxes using [Query](!docs!/learn/fundamentals/query) and the [Tax Module](../commerce-modules/tax/page.mdx)
3877
3878 ```ts
3879 import {
3880 HttpTypes,
3881 TaxableItemDTO,
3882 ItemTaxLineDTO,
3883 } from "@medusajs/framework/types"
3884 import {
3885 QueryContext,
3886 calculateAmountsWithTax,
3887 } from "@medusajs/framework/utils"
3888 // other imports...
3889
3890 // ...
3891 const asTaxItem = (product: HttpTypes.StoreProduct): TaxableItemDTO[] => {
3892 return product.variants
3893 ?.map((variant) => {
3894 if (!variant.calculated_price) {
3895 return
3896 }
3897
3898 return {
3899 id: variant.id,
3900 product_id: product.id,
3901 product_name: product.title,
3902 product_categories: product.categories?.map((c) => c.name),
3903 product_category_id: product.categories?.[0]?.id,
3904 product_sku: variant.sku,
3905 product_type: product.type,
3906 product_type_id: product.type_id,
3907 quantity: 1,
3908 unit_price: variant.calculated_price.calculated_amount,
3909 currency_code: variant.calculated_price.currency_code,
3910 }
3911 })
3912 .filter((v) => !!v) as unknown as TaxableItemDTO[]
3913 }
3914
3915 const { data: products } = await query.graph({
3916 entity: "product",
3917 fields: [
3918 "*",
3919 "variants.*",
3920 "variants.calculated_price.*",
3921 ],
3922 filters: {
3923 id: "prod_123",
3924 },
3925 context: {
3926 variants: {
3927 calculated_price: QueryContext({
3928 region_id: "region_123",
3929 currency_code: "usd",
3930 }),
3931 },
3932 },
3933 })
3934
3935 const taxLines = (await taxModuleService.getTaxLines(
3936 products.map(asTaxItem).flat(),
3937 {
3938 // example of context properties. You can pass other ones.
3939 address: {
3940 country_code,
3941 },
3942 }
3943 )) as unknown as ItemTaxLineDTO[]
3944
3945 const taxLinesMap = new Map<string, ItemTaxLineDTO[]>()
3946 taxLines.forEach((taxLine) => {
3947 const variantId = taxLine.line_item_id
3948 if (!taxLinesMap.has(variantId)) {
3949 taxLinesMap.set(variantId, [])
3950 }
3951
3952 taxLinesMap.get(variantId)?.push(taxLine)
3953 })
3954
3955 products.forEach((product) => {
3956 product.variants?.forEach((variant) => {
3957 if (!variant.calculated_price) {
3958 return
3959 }
3960
3961 const taxLinesForVariant = taxLinesMap.get(variant.id) || []
3962 const { priceWithTax, priceWithoutTax } = calculateAmountsWithTax({
3963 taxLines: taxLinesForVariant,
3964 amount: variant.calculated_price!.calculated_amount!,
3965 includesTax:
3966 variant.calculated_price!.is_calculated_price_tax_inclusive!,
3967 })
3968
3969 // do something with prices...
3970 })
3971 })
3972 ```
3973
3974 Learn more in [this documentation](../commerce-modules/product/guides/price-with-taxes/page.mdx).
3975
3976 ### Invite Users
3977
3978 To invite a user using the [User Module](../commerce-modules/user/page.mdx):
3979
3980 ```ts
3981 const invite = await userModuleService.createInvites({
3982 email: "user@example.com",
3983 })
3984 ```
3985
3986 ### Accept User Invite
3987
3988 To accept an invite and create a user using the [User Module](../commerce-modules/user/page.mdx):
3989
3990 ```ts
3991 const invite =
3992 await userModuleService.validateInviteToken(inviteToken)
3993
3994 await userModuleService.updateInvites({
3995 id: invite.id,
3996 accepted: true,
3997 })
3998
3999 const user = await userModuleService.createUsers({
4000 email: invite.email,
4001 })
4002 ```