1 ---
2 sidebar_label: "Build Wishlist Plugin"
3 tags:
4 - product
5 - tutorial
6 - server
7 products:
8 - product
9 - customer
10 - sales channel
11 ---
12
13 import { Github, PlaySolid } from "@medusajs/icons"
14 import { Prerequisites, CardList, WorkflowDiagram } from "docs-ui"
15
16 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1737564127/Medusa%20Resources/plugins-wishlist_ktut0d.jpg"
17
18 export const metadata = {
19 title: `How to Build a Wishlist Plugin`,
20 openGraph: {
21 images: [
22 {
23 url: ogImage,
24 width: 1600,
25 height: 836,
26 type: "image/jpeg"
27 }
28 ],
29 },
30 twitter: {
31 images: [
32 {
33 url: ogImage,
34 width: 1600,
35 height: 836,
36 type: "image/jpeg"
37 }
38 ]
39 }
40 }
41
42 # {metadata.title}
43
44 In this guide, you'll learn how to build a wishlist [plugin](!docs!/learn/fundamentals/plugins) in Medusa.
45
46 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx) which are available out-of-the-box.
47
48 Customers browsing your store may be interested in a product but not ready to buy it yet. They may want to save the product for later or share it with friends and family. A wishlist feature allows customers to save products they like and access them later.
49
50 This guide will teach you how to:
51
52 - Install and set up a Medusa application project.
53 - Install and set up a Medusa plugin.
54 - Implement the wishlist features in the plugin.
55 - Features include allowing customers to add products to a wishlist, view and manage their wishlist, and share their wishlist.
56 - Test and use the wishlist plugin in your Medusa application.
57
58 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
59
60 <CardList items={[
61 {
62 href: "https://github.com/medusajs/examples/tree/main/wishlist-plugin",
63 title: "Wishlist Plugin Example Repository",
64 text: "Find the full code for this guide in, with the plugin to install.",
65 icon: Github,
66 },
67 {
68 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1737459635/OpenApi/Wishlist_Postman_gjk7mn.yml",
69 title: "OpenApi Specs for Postman",
70 text: "Import this OpenApi Specs file into tools like Postman.",
71 icon: PlaySolid,
72 },
73 ]} />
74
75 ---
76
77 ## Step 1: Install a Medusa Application
78
79 You'll first install a Medusa application that exposes core commerce features through REST APIs. You'll later install the wishlist plugin in this application to test it out.
80
81 <Prerequisites items={[
82 {
83 text: "Node.js v20.19.0+ or v22.12.0+",
84 link: "https://nodejs.org/en/download"
85 },
86 {
87 text: "Git CLI tool",
88 link: "https://git-scm.com/downloads"
89 },
90 {
91 text: "PostgreSQL",
92 link: "https://www.postgresql.org/download/"
93 }
94 ]} />
95
96 Start by installing the Medusa application on your machine with the following command:
97
98 ```bash npx2yarnExec
99 npx create-medusa-app@latest
100 ```
101
102 You'll be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
103
104 Afterward, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
105
106 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard.
107
108 <Note title="Ran into Errors">
109
110 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
111
112 </Note>
113
114 <Note>
115
116 In this guide, all file paths are relative to the `apps/backend` directory of your Medusa project.
117
118 </Note>
119
120 ---
121
122 ## Step 2: Install a Medusa Plugin Project
123
124 A plugin is a package of reusable Medusa customizations that you can install in any Medusa application. You can add in the plugin [API Routes](!docs!/learn/fundamentals/api-routes), [Workflows](!docs!/learn/fundamentals/workflows), and other customizations, as you'll see in this guide. Afterward, you can test it out locally in a Medusa application, then publish it to npm to install and use it in any Medusa application.
125
126 <Note>
127
128 Learn more about plugins in [this documentation](!docs!/learn/fundamentals/plugins).
129
130 </Note>
131
132 A Medusa plugin is set up in a different project, giving you the flexibility in building and publishing it, while providing you with the tools to test it out locally in a Medusa application.
133
134 To create a new Medusa plugin project, run the following command in a directory different than that of the Medusa application:
135
136 ```bash npx2yarnExec
137 npx create-medusa-app@latest medusa-plugin-wishlist --plugin
138 ```
139
140 Where `medusa-plugin-wishlist` is the name of the plugin's directory and the name set in the plugin's `package.json`. So, if you wish to publish it to NPM later under a different name, you can change it here in the command or later in `package.json`.
141
142 Once the installation process is done, a new directory named `medusa-plugin-wishlist` will be created with the plugin project files.
143
144 ![Directory structure of a plugin project](https://res.cloudinary.com/dza7lstvk/image/upload/v1737019441/Medusa%20Book/project-dir_q4xtri.jpg)
145
146 ---
147
148 ## Step 3: Set up Plugin in Medusa Application
149
150 Before you start your development, you'll set up the plugin in the Medusa application you installed in the first step. This will allow you to test the plugin during your development process.
151
152 In the plugin's directory, run the following command to publish the plugin to the local package registry:
153
154 ```bash npx2yarn title="Plugin project"
155 npx medusa plugin:publish
156 ```
157
158 This command uses [Yalc](https://github.com/wclr/yalc) under the hood to publish the plugin to a local package registry. The plugin is published locally under the name you specified in `package.json`.
159
160 Next, you'll install the plugin in the Medusa application from the local registry.
161
162 <Note>
163
164 If you've installed your Medusa project before v2.3.1, you must install [yalc](https://github.com/wclr/yalc) as a development dependency first.
165
166 </Note>
167
168 Run the following command in the `apps/backend` directory to install the plugin:
169
170 ```bash npx2yarn title="Medusa application"
171 npx medusa plugin:add medusa-plugin-wishlist
172 ```
173
174 This command installs the plugin in the Medusa application from the local package registry.
175
176 Next, register the plugin in the `medusa-config.ts` file of the Medusa application:
177
178 ```ts title="medusa-config.ts"
179 module.exports = defineConfig({
180 // ...
181 plugins: [
182 {
183 resolve: "medusa-plugin-wishlist",
184 options: {},
185 },
186 ],
187 })
188 ```
189
190 Finally, to ensure your plugin's changes are constantly published to the local registry, simplifying your testing process, keep the following command running in the plugin project during development:
191
192 ```bash npx2yarn title="Plugin project"
193 npx medusa plugin:develop
194 ```
195
196 ---
197
198 ## Step 4: Implement Wishlist Module
199
200 To add custom tables to the database, which are called data models, you create a module. A module is a package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
201
202 While you can create modules outside of a plugin and install them in the Medusa application, plugins allow you to bundle modules with other customizations, such as API routes and workflows.
203
204 In this step, you'll create a Wishlist Module within the wishlist plugin. This module adds custom data models for wishlists and their items, which you'll use in later steps to store a customer's wishlist.
205
206 <Note>
207
208 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
209
210 </Note>
211
212 ### Create Module Directory
213
214 A module is created under the `src/modules` directory of your plugin. So, create the directory `src/modules/wishlist`.
215
216 ![Diagram showcasing the module directory to create](https://res.cloudinary.com/dza7lstvk/image/upload/v1737461182/Medusa%20Resources/wishlist-1_z3kzfv.jpg)
217
218 ### Create Data Models
219
220 A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
221
222 <Note>
223
224 Learn more about data models in [this documentation](!docs!/learn/fundamentals/modules#1-create-data-model).
225
226 </Note>
227
228 In the Wishlist Module, you'll create two data models: `Wishlist` and `WishlistItem`. The `Wishlist` model represents a customer's wishlist, while the `WishlistItem` model represents a product in the wishlist.
229
230 Starting with the `Wishlist` model, create a file `src/modules/wishlist/models/wishlist.ts` with the following content:
231
232 ![Directory structure after adding the Wishlist model](https://res.cloudinary.com/dza7lstvk/image/upload/v1737461304/Medusa%20Resources/wishlist-2_co2lht.jpg)
233
234 ```ts title="src/modules/wishlist/models/wishlist.ts"
235 import { model } from "@medusajs/framework/utils"
236 import { WishlistItem } from "./wishlist-item"
237
238 export const Wishlist = model.define("wishlist", {
239 id: model.id().primaryKey(),
240 customer_id: model.text(),
241 sales_channel_id: model.text(),
242 items: model.hasMany(() => WishlistItem, {
243 mappedBy: "wishlist",
244 }),
245 })
246 .indexes([
247 {
248 on: ["customer_id", "sales_channel_id"],
249 unique: true,
250 },
251 ])
252 ```
253
254 The `Wishlist` model has the following properties:
255
256 - `id`: A unique identifier for the wishlist.
257 - `customer_id`: The ID of the customer who owns the wishlist.
258 - `sales_channel_id`: The ID of the sales channel where the wishlist is created. In Medusa, product availability can differ between sales channels. This ensures only products available in the customer's sales channel are added to the wishlist.
259 - `items`: A relation to the `WishlistItem` model, representing the products in the wishlist. You'll add this data model next.
260
261 <Note>
262
263 Learn more about data model [properties](!docs!/learn/fundamentals/data-models/properties) and [relations](!docs!/learn/fundamentals/data-models/relationships).
264
265 </Note>
266
267 You also define a unique index on the `customer_id` and `sales_channel_id` columns to ensure a customer can only have one wishlist per sales channel.
268
269 <Note>
270
271 Learn more about data model indexes in [this documentation](!docs!/learn/fundamentals/data-models/indexes).
272
273 </Note>
274
275 Next, create the `WishlistItem` model in the file `src/modules/wishlist/models/wishlist-item.ts`:
276
277 ![Directory structure after adding the WishlistItem model](https://res.cloudinary.com/dza7lstvk/image/upload/v1737461521/Medusa%20Resources/wishlist-3_fxcjxy.jpg)
278
279 ```ts title="src/modules/wishlist/models/wishlist-item.ts"
280 import { model } from "@medusajs/framework/utils"
281 import { Wishlist } from "./wishlist"
282
283 export const WishlistItem = model.define("wishlist_item", {
284 id: model.id().primaryKey(),
285 product_variant_id: model.text(),
286 wishlist: model.belongsTo(() => Wishlist, {
287 mappedBy: "items",
288 }),
289 })
290 .indexes([
291 {
292 on: ["product_variant_id", "wishlist_id"],
293 unique: true,
294 },
295 ])
296 ```
297
298 The `WishlistItem` model has the following properties:
299
300 - `id`: A unique identifier for the wishlist item.
301 - `product_variant_id`: The ID of the product variant in the wishlist.
302 - `wishlist`: A relation to the `Wishlist` model, representing the wishlist the item belongs to.
303
304 You also define a unique index on the `product_variant_id` and `wishlist_id` columns to ensure a product variant is added to the wishlist only once. The `wishlist_id` column is available as a by-product of the `belongsTo` relation.
305
306 ### Create Service
307
308 You define data-management methods of your data models in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can perform database operations.
309
310 <Note>
311
312 Learn more about services in [this documentation](!docs!/learn/fundamentals/modules#2-create-service).
313
314 </Note>
315
316 In this section, you'll create the Wishlist Module's service that's used to manage wishlists and wishlist items. Create the file `src/modules/wishlist/service.ts` with the following content:
317
318 ![Directory structure after adding the service file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737461698/Medusa%20Resources/wishlist-4_j5ka26.jpg)
319
320 ```ts title="src/modules/wishlist/service.ts"
321 import { MedusaService } from "@medusajs/framework/utils"
322 import { Wishlist } from "./models/wishlist"
323 import { WishlistItem } from "./models/wishlist-item"
324
325 export default class WishlistModuleService extends MedusaService({
326 Wishlist,
327 WishlistItem,
328 }) {}
329 ```
330
331 The `WishlistModuleService` extends `MedusaService` from the Modules SDK which generates a class with data-management methods for your module's data models. This saves you time on implementing Create, Read, Update, and Delete (CRUD) methods.
332
333 So, the `WishlistModuleService` class now has methods like `createWishlists` and `retrieveWishlist`.
334
335 <Note>
336
337 Find all methods generated by the `MedusaService` in [this reference](../../../service-factory-reference/page.mdx).
338
339 </Note>
340
341 You'll use this service in a later method to store and manage wishlists and wishlist items in other customizations.
342
343 ### Export Module Definition
344
345 The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
346
347 So, create the file `src/modules/wishlist/index.ts` with the following content:
348
349 ![Directory structure after adding the module definition file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737461829/Medusa%20Resources/wishlist-5_mb4tjf.jpg)
350
351 ```ts title="src/modules/wishlist/index.ts"
352 import WishlistModuleService from "./service"
353 import { Module } from "@medusajs/framework/utils"
354
355 export const WISHLIST_MODULE = "wishlist"
356
357 export default Module(WISHLIST_MODULE, {
358 service: WishlistModuleService,
359 })
360 ```
361
362 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
363
364 1. The module's name, which is `wishlist`.
365 2. An object with a required property `service` indicating the module's service.
366
367 You'll later use the module's service to manage wishlists and wishlist items in other customizations.
368
369 ### Generate Migrations
370
371 Since data models represent tables in the database, you define how they're created in the database with migrations. A migration is a TypeScript or JavaScript file that defines database changes made by a module.
372
373 <Note>
374
375 Learn more about migrations in [this documentation](!docs!/learn/fundamentals/modules#5-generate-migrations).
376
377 </Note>
378
379 Medusa's CLI tool generates the migrations for you. To generate a migration for the Wishlist Module, run the following command in the plugin project:
380
381 ```bash npx2yarn title="Plugin project"
382 npx medusa plugin:db:generate
383 ```
384
385 You'll now have a `migrations` directory under `src/modules/wishlist` that holds the generated migration.
386
387 Then, to reflect these migrations on the database of the Medusa application using this module, run the following command:
388
389 <Note>
390
391 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
392
393 </Note>
394
395 ```bash npx2yarn title="Medusa application"
396 npx medusa db:migrate
397 ```
398
399 The tables of the Wishlist Module's data models are now created in the database.
400
401 ---
402
403 ## Step 5: Link Wishlist Data Models with Core Models
404
405 The Wishlist Module's data models store IDs of records in data models implemented in Medusa's core Commerce Modules, such as the ID of a customer or a product variant.
406
407 However, modules are [isolated](!docs!/learn/fundamentals/modules/isolation) to ensure they're re-usable and don't have side effects when integrated into the Medusa application. So, to build associations between modules, you define [module links](!docs!/learn/fundamentals/module-links). A Module link associates two modules' data models while maintaining module isolation.
408
409 In this section, you'll link the `Wishlist` data model to the [Customer Module](../../../commerce-modules/customer/page.mdx)'s `Customer` data model, and to the [Sales Channel](../../../commerce-modules/sales-channel/page.mdx) Module's `SalesChannel` data model. You'll also link the `WishlistItem` data model to the [Product Module](../../../commerce-modules/product/page.mdx)'s `ProductVariant` data model.
410
411 <Note>
412
413 Learn more about module links in [this documentation](!docs!/learn/fundamentals/module-links).
414
415 </Note>
416
417 To create the link between the `Wishlist` data model and the `Customer` data model, create the file `src/modules/wishlist/links/wishlist-customer.ts` with the following content:
418
419 ![Directory structure after adding the link file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737462649/Medusa%20Resources/wishlist-6_xqytog.jpg)
420
421 ```ts title="src/modules/wishlist/links/wishlist-customer.ts"
422 import { defineLink } from "@medusajs/framework/utils"
423 import WishlistModule from "../modules/wishlist"
424 import CustomerModule from "@medusajs/medusa/customer"
425
426 export default defineLink(
427 {
428 linkable: WishlistModule.linkable.wishlist.id,
429 field: "customer_id",
430 },
431 CustomerModule.linkable.customer,
432 {
433 readOnly: true,
434 }
435 )
436 ```
437
438 You define a link using `defineLink` from the Modules SDK. It accepts three parameters:
439
440 1. The first data model part of the link, which is the Wishlist Module's `wishlist` data model. A module has a special `linkable` property that contain link configurations for its data models. You also specify the field that points to the customer.
441 1. The second data model part of the link, which is the Customer Module's `customer` data model.
442 3. An object of configurations for the module link. By default, Medusa creates a table in the database to represent the link you define. However, in this guide, you only want this link to retrieve the customer associated with a wishlist. So, you enable `readOnly` telling Medusa not to create a table for this link.
443
444 Next, to create the link between the `Wishlist` data model and the `SalesChannel` data model, create the file `src/modules/wishlist/links/wishlist-sales-channel.ts` with the following content:
445
446 ![Directory structure after adding the link file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737462829/Medusa%20Resources/wishlist-7_ddiwxy.jpg)
447
448 ```ts title="src/modules/wishlist/links/wishlist-sales-channel.ts"
449 import { defineLink } from "@medusajs/framework/utils"
450 import WishlistModule from "../modules/wishlist"
451 import SalesChannelModule from "@medusajs/medusa/sales-channel"
452
453 export default defineLink(
454 {
455 linkable: WishlistModule.linkable.wishlist.id,
456 field: "sales_channel_id",
457 },
458 SalesChannelModule.linkable.salesChannel,
459 {
460 readOnly: true,
461 }
462 )
463 ```
464
465 You define a link between the `Wishlist` data model and the `SalesChannel` data model in the same way as the previous link.
466
467 Finally, to create the link between the `WishlistItem` data model and the `ProductVariant` data model, create the file `src/modules/wishlist/links/wishlist-product.ts` with the following content:
468
469 ![Directory structure after adding the link file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737467010/Medusa%20Resources/wishlist-8_hgoaby.jpg)
470
471 ```ts title="src/modules/wishlist/links/wishlist-product.ts"
472 import { defineLink } from "@medusajs/framework/utils"
473 import WishlistModule from "../modules/wishlist"
474 import ProductModule from "@medusajs/medusa/product"
475
476 export default defineLink(
477 {
478 linkable: WishlistModule.linkable.wishlistItem.id,
479 field: "product_variant_id",
480 },
481 ProductModule.linkable.productVariant,
482 {
483 readOnly: true,
484 }
485 )
486 ```
487
488 You define a link between the `WishlistItem` data model and the `ProductVariant` data model in the same way as the previous links.
489
490 In the next steps, you'll see how these links allow you to retrieve the resources associated with a wishlist or wishlist item.
491
492 ---
493
494 ## Step 6: Create Wishlist Workflow
495
496 The first feature you'll add to the wishlist plugin is the ability to create a wishlist for a customer. You'll implement this feature in a workflow.
497
498 A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint.
499
500 In this section, you'll create a workflow that creates a wishlist for a customer. Later, you'll execute this workflow from an API route.
501
502 <Note>
503
504 Learn more about workflows in [this documentation](!docs!/learn/fundamentals/workflows)
505
506 </Note>
507
508 The workflow has the following steps:
509
510 <WorkflowDiagram
511 workflow={{
512 name: "createWishlistWorkflow",
513 steps: [
514 {
515 type: "step",
516 name: "validateCustomerCreateWishlistStep",
517 description: "Validate that the customer doesn't have an existing wishlist.",
518 depth: 1
519 },
520 {
521 type: "step",
522 name: "createWishlistStep",
523 description: "Create a wishlist for the customer.",
524 depth: 1
525 },
526 ]
527 }}
528 hideLegend
529 />
530
531 You'll implement the steps before implementing the workflow.
532
533 ### validateCustomerCreateWishlistStep
534
535 The first step in the workflow will validate that a customer doesn't have an existing workflow. If not valid, the step will throw an error, stopping the workflow's execution.
536
537 To create the step, create the file `src/workflows/steps/validate-customer-create-wishlist.ts` with the following content:
538
539 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737467678/Medusa%20Resources/wishlist-9_lzlifn.jpg)
540
541 export const validateCustomerWishlistHighlights = [
542 ["18", "graph", "Retrieve the wishlist based on the specified customer ID."],
543 ["26", "", "Throw an error if the customer already has a wishlist."],
544 ["34", "graph", "Retrieve the customer based on the specified customer ID."],
545 ["33", "", "Throw an error if the customer doesn't exist."],
546 ]
547
548 ```ts title="src/workflows/steps/validate-customer-create-wishlist.ts" highlights={validateCustomerWishlistHighlights}
549 import {
550 MedusaError,
551 ContainerRegistrationKeys,
552 } from "@medusajs/framework/utils"
553 import { createStep } from "@medusajs/framework/workflows-sdk"
554
555 type ValidateCustomerCreateWishlistStepInput = {
556 customer_id: string
557 }
558
559 export const validateCustomerCreateWishlistStep = createStep(
560 "validate-customer-create-wishlist",
561 async ({ customer_id }: ValidateCustomerCreateWishlistStepInput, { container }) => {
562 const query = container.resolve(
563 ContainerRegistrationKeys.QUERY
564 )
565
566 const { data } = await query.graph({
567 entity: "wishlist",
568 fields: ["*"],
569 filters: {
570 customer_id: customer_id,
571 },
572 })
573
574 if (data.length) {
575 throw new MedusaError(
576 MedusaError.Types.NOT_FOUND,
577 "Customer already has a wishlist"
578 )
579 }
580
581 // check that customer exists
582 const { data: customers } = await query.graph({
583 entity: "customer",
584 fields: ["*"],
585 filters: {
586 id: customer_id,
587 },
588 })
589
590 if (customers.length === 0) {
591 throw new MedusaError(
592 MedusaError.Types.INVALID_DATA,
593 "Specified customer was not found"
594 )
595 }
596 }
597 )
598 ```
599
600 You create a step using `createStep` from the Workflows SDK. It accepts two parameters:
601
602 1. The step's name, which is `validate-customer-create-wishlist`.
603 1. An async function that executes the step's logic. The function receives two parameters:
604 - The input data for the step, which in this case is an object having a `customer_id` property.
605 - An object holding the workflow's context, including the [Medusa Container](!docs!/learn/fundamentals/medusa-container) that allows you to resolve Framework and commerce tools.
606
607 In the step function, you use [Query](!docs!/learn/fundamentals/query) to retrieve the wishlist based on the specified customer ID. If a wishlist exists, you throw an error, stopping the workflow's execution.
608
609 You also try to retrieve the customer, and if they don't exist, you throw an error.
610
611 ### createWishlistStep
612
613 The second step in the workflow will create a wishlist for the customer. To create the step, create the file `src/workflows/steps/create-wishlist.ts` with the following content:
614
615 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737467998/Medusa%20Resources/wishlist-10_xex4d0.jpg)
616
617 export const createWishlistStepHighlights = [
618 ["13", "wishlistModuleService", "Resolve the Wishlist Module's service from the container."],
619 ["16", "createWishlists", "Create the wishlist."],
620 ["18", "wishlist", "Return the wishlist"],
621 ["18", "wishlist.id", "Pass the wishlist's ID to the compensation function."],
622 ["27", "deleteWishlists", "Delete the wishlist if an error occurs in the workflow."]
623 ]
624
625 ```ts title="src/workflows/steps/create-wishlist.ts" highlights={createWishlistStepHighlights}
626 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
627 import { WISHLIST_MODULE } from "../../modules/wishlist"
628 import WishlistModuleService from "../../modules/wishlist/service"
629
630 type CreateWishlistStepInput = {
631 customer_id: string
632 sales_channel_id: string
633 }
634
635 export const createWishlistStep = createStep(
636 "create-wishlist",
637 async (input: CreateWishlistStepInput, { container }) => {
638 const wishlistModuleService: WishlistModuleService =
639 container.resolve(WISHLIST_MODULE)
640
641 const wishlist = await wishlistModuleService.createWishlists(input)
642
643 return new StepResponse(wishlist, wishlist.id)
644 },
645 async (id, { container }) => {
646 if (!id) {
647 return
648 }
649 const wishlistModuleService: WishlistModuleService =
650 container.resolve(WISHLIST_MODULE)
651
652 await wishlistModuleService.deleteWishlists(id)
653 }
654 )
655 ```
656
657 This step accepts the IDs of the customer and the sales channel as input. In the step function, you resolve the Wishlist Module's service from the container and use its generated `createWishlists` method to create the wishlist, passing it the input as a parameter.
658
659 Steps that return data must return them in a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
660
661 - The data to return, which in this case is the created wishlist.
662 - The data to pass to the compensation function, which in this case is the wishlist's ID.
663
664 The compensation function is an optional third parameter of `createStep`. It defines rollback logic that's executed when an error occurs during the workflow's execution. In the compensation function, you undo the actions you performed in the step function.
665
666 The compensation function accepts as a first parameter the data passed as a second parameter to the `StepResponse` returned by the step function, which in this case is the wishlist's ID. In the compensation function, you resolve the Wishlist Module's service from the container and use its generated `deleteWishlists` method to delete the wishlist.
667
668 <Note>
669
670 Learn more about the generated [create](../../../service-factory-reference/methods/create/page.mdx) and [delete](../../../service-factory-reference/methods/delete/page.mdx) methods.
671
672 </Note>
673
674 ### Add createWishlistWorkflow
675
676 You can now add the `createWishlistWorkflow` to the plugin. Create the file `src/workflows/create-wishlist.ts` with the following content:
677
678 ![Directory structure after adding the workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737468333/Medusa%20Resources/wishlist-11_absftb.jpg)
679
680 export const createWishlistWorkflowHighlights = [
681 ["13", "validateCustomerCreateWishlistStep", "Validate that the customer doesn't already have a wishlist."],
682 ["17", "createWishlistStep", "Create the wishlist."],
683 ["20", "wishlist", "Return the wishlist."]
684 ]
685
686 ```ts title="src/workflows/create-wishlist.ts" highlights={createWishlistWorkflowHighlights}
687 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
688 import { validateCustomerCreateWishlistStep } from "./steps/validate-customer-create-wishlist"
689 import { createWishlistStep } from "./steps/create-wishlist"
690
691 type CreateWishlistWorkflowInput = {
692 customer_id: string
693 sales_channel_id: string
694 }
695
696 export const createWishlistWorkflow = createWorkflow(
697 "create-wishlist",
698 (input: CreateWishlistWorkflowInput) => {
699 validateCustomerCreateWishlistStep({
700 customer_id: input.customer_id,
701 })
702
703 const wishlist = createWishlistStep(input)
704
705 return new WorkflowResponse({
706 wishlist,
707 })
708 }
709 )
710 ```
711
712 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
713
714 It accepts as a second parameter a constructor function, which is the workflow's implementation. In the workflow, you:
715
716 - Execute the `validateCustomerCreateWishlistStep` step to validate that the customer doesn't have an existing wishlist.
717 - Execute the `createWishlistStep` step to create the wishlist.
718
719 <Note title="Tip">
720
721 A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for variable manipulation. Learn more about these constraints in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints).
722
723 </Note>
724
725 Workflows must return an instance of `WorkflowResponse`, passing as a parameter the data to return to the workflow's executor. The workflow returns an object having a `wishlist` property, which is the created wishlist.
726
727 You'll execute this workflow in an API route in the next step.
728
729 ---
730
731 ## Step 7: Create Wishlist API Route
732
733 Now that you implemented the flow to create a wishlist for a customer, you'll create an API route that exposes this functionality.
734
735 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create a `POST` API route at the path `/store/customers/me/wishlists` that executes the workflow from the previous step.
736
737 <Note>
738
739 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
740
741 </Note>
742
743 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
744
745 So, to create the `/store/customers/me/wishlists` API route, create the file `src/api/store/customers/me/wishlists/route.ts` with the following content:
746
747 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737468859/Medusa%20Resources/wishlist-12_gvvb9z.jpg)
748
749 ```ts title="src/api/store/customers/me/wishlists/route.ts"
750 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
751 import { createWishlistWorkflow } from "../../../../../workflows/create-wishlist"
752 import { MedusaError } from "@medusajs/framework/utils"
753
754 export async function POST(
755 req: AuthenticatedMedusaRequest,
756 res: MedusaResponse
757 ) {
758 if (!req.publishable_key_context?.sales_channel_ids.length) {
759 throw new MedusaError(
760 MedusaError.Types.INVALID_DATA,
761 "At least one sales channel ID is required to be associated with the publishable API key in the request header."
762 )
763 }
764 const { result } = await createWishlistWorkflow(req.scope)
765 .run({
766 input: {
767 customer_id: req.auth_context.actor_id,
768 sales_channel_id: req.publishable_key_context?.sales_channel_ids[0],
769 },
770 })
771
772 res.json({
773 wishlist: result.wishlist,
774 })
775 }
776 ```
777
778 Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/customers/me/wishlists`. The route handler function accepts two parameters:
779
780 1. A request object with details and context about the request, such as authenticated customer details.
781 2. A response object to manipulate and send the response.
782
783 API routes implemented under the `/store` path require passing a publishable API key in the header of the request. The publishable API key is created by an admin user and is associated with one or more sales channels. In the route handler function, you validate that the request has at least one sales channel ID associated with the publishable API key. You'll use that sales channel ID with the wishlist you're creating.
784
785 Also, API routes implemented under the `/store/customers/me` path are only accessible by authenticated customers. You access the ID of the authenticated customer using the `auth_context.actor_id` property of the request object.
786
787 In the route handler function, you execute the `createWishlistWorkflow`, passing the authenticated customer ID and the sales channel ID as input. The workflow returns an object having a `result` property, which is the data returned by the workflow. You return the created wishlist in the response.
788
789 ### Test API Route
790
791 You'll now test that this API route defined in the plugin is working as expected using the Medusa application you installed in the first step.
792
793 <Note>
794
795 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
796
797 </Note>
798
799 In the `apps/backend` directory, run the following command to start the development server:
800
801 ```bash npm2yarn
802 npm run dev
803 ```
804
805 ### Retrieve Publishable API Key
806
807 Before sending the request, you need to obtain a publishable API key. So, open the Medusa Admin at `http://localhost:9000/app` and log in with the user you created earlier.
808
809 To access your application's API keys in the admin, go to Settings -> Publishable API Keys. You'll have an API key created by default, which is associated with the default sales channel. You can use this publishable API key in the request header.
810
811 ![In the admin, click on Publishable API key in the sidebar. A table will show your API keys and allow you to create one.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230421/Medusa%20Resources/Screenshot_2024-12-03_at_2.53.07_PM_gau9jy.png)
812
813 ### Retrieve Authenticated Customer Token
814
815 Then, you need an authentication token of a registered customer. To create a customer, first, send the following request to the Medusa application:
816
817 ```bash
818 curl -X POST 'http://localhost:9000/auth/customer/emailpass/register' \
819 --header 'Content-Type: application/json' \
820 --data-raw '{
821 "email": "customer@gmail.com",
822 "password": "supersecret"
823 }'
824 ```
825
826 This API route obtains a registration token for the specified email and password in the request body.
827
828 Next, use that token to register the customer:
829
830 ```bash
831 curl -X POST 'http://localhost:9000/store/customers' \
832 --header 'Content-Type: application/json' \
833 -H 'x-publishable-api-key: {api_key}' \
834 --header 'Authorization: Bearer {token}' \
835 --data-raw '{
836 "email": "customer@gmail.com"
837 }'
838 ```
839
840 Make sure to replace `{api_key}` with the publishable API key you copied from the settings, and `{token}` with the token received from the previous request.
841
842 This will create a customer. You can now obtain the customer's authentication token by sending the following request:
843
844 ```bash
845 curl -X POST 'http://localhost:9000/auth/customer/emailpass' \
846 --header 'Content-Type: application/json' \
847 --data-raw '{
848 "email": "customer@gmail.com",
849 "password": "supersecret"
850 }'
851 ```
852
853 This API route will return an authentication token for the customer. You'll use this token in the header of the following requests.
854
855 ### Send Request to Create Wishlist
856
857 Finally, send a `POST` request to the `/store/customers/me/wishlists` API route to create a wishlist for the authenticated customer:
858
859 ```bash
860 curl -X POST 'localhost:9000/store/customers/me/wishlists' \
861 --header 'x-publishable-api-key: {api_key}' \
862 --header 'Authorization: Bearer {token}'
863 ```
864
865 Make sure to replace `{api_key}` with the publishable API key you copied from the settings, and `{token}` with the authenticated customer token.
866
867 You'll receive in the response the created wishlist.
868
869 ---
870
871 ## Step 8: Retrieve Wishlist API Route
872
873 In this step, you'll add an API route to retrieve a customer's wishlist. You'll create a `GET` API route at the path `/store/customers/me/wishlists` that retrieves the wishlist of the authenticated customer.
874
875 So, add to the `src/api/store/customers/me/wishlists/route.ts` the following:
876
877 ```ts title="src/api/store/customers/me/wishlists/route.ts"
878 export async function GET(
879 req: AuthenticatedMedusaRequest,
880 res: MedusaResponse
881 ) {
882 const query = req.scope.resolve(
883 ContainerRegistrationKeys.QUERY
884 )
885
886 const { data } = await query.graph({
887 entity: "wishlist",
888 fields: ["*", "items.*", "items.product_variant.*"],
889 filters: {
890 customer_id: req.auth_context.actor_id,
891 },
892 })
893
894 if (!data.length) {
895 throw new MedusaError(
896 MedusaError.Types.NOT_FOUND,
897 "No wishlist found for customer"
898 )
899 }
900
901 return res.json({
902 wishlist: data[0],
903 })
904 }
905 ```
906
907 In this route handler function, you use [Query](!docs!/learn/fundamentals/query) to retrieve the wishlist of the authenticated customer. For each wishlist, you retrieve its items, and the product variants of those items.
908
909 If the wishlist doesn't exist, you throw an error. Otherwise, you return the wishlist in the response.
910
911 ### Test Retrieve Wishlist API Route
912
913 To test the API route, start the Medusa application.
914
915 <Note>
916
917 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
918
919 </Note>
920
921 Then, send a `GET` request to the `/store/customers/me/wishlists` API route:
922
923 ```bash
924 curl 'localhost:9000/store/customers/me/wishlists' \
925 --header 'x-publishable-api-key: {api_key}' \
926 --header 'Authorization: Bearer {token}'
927 ```
928
929 Make sure to replace:
930
931 - `{api_key}` with the publishable API key you copied from the settings, as explained in the [previous step](#retrieve-publishable-api-key).
932 - `{token}` with the authenticated customer token you received from the [previous step](#retrieve-authenticated-customer-token).
933
934 You'll receive in the response the wishlist of the authenticated customer.
935
936 ---
937
938 ## Step 9: Add Item to Wishlist API Route
939
940 Next, you'll add the functionality to add an item to a wishlist. You'll first define a workflow that implements this functionality, then create an API route that executes the workflow.
941
942 ### Add Item to Wishlist Workflow
943
944 The workflow to add an item to a wishlist has the following steps:
945
946 <WorkflowDiagram
947 workflow={{
948 name: "createWishlistItemWorkflow",
949 steps: [
950 {
951 type: "step",
952 name: "useQueryGraphStep",
953 description: "Retrieve the wishlist of a customer.",
954 depth: 1,
955 link: "/references/helper-steps/useQueryGraphStep"
956 },
957 {
958 type: "step",
959 name: "validateWishlistExistsStep",
960 description: "Validate that the customer's wishlist exists.",
961 depth: 1
962 },
963 {
964 type: "step",
965 name: "validateWishlistSalesChannelStep",
966 description: "Validate that the wishlist belongs to the specified sales channel.",
967 depth: 1
968 },
969 {
970 type: "step",
971 name: "validateVariantWishlistStep",
972 description: "Validate that the specified variant is not already in the wishlist.",
973 depth: 1
974 },
975 {
976 type: "step",
977 name: "createWishlistItemStep",
978 description: "Create the wishlist item.",
979 depth: 1
980 },
981 {
982 type: "step",
983 name: "useQueryGraphStep",
984 description: "Retrieve the wishlist again with the new item added.",
985 depth: 1,
986 link: "/references/helper-steps/useQueryGraphStep"
987 },
988 ]
989 }}
990 hideLegend
991 />
992
993 The `useQueryGraphStep` is from Medusa's workflows package. So, you'll only implement the other steps.
994
995 #### validateWishlistExistsStep
996
997 The second step in the workflow validates that the customer's wishlist, retrieved in the first step, exists.
998
999 To create the step, create the file `src/workflows/steps/validate-wishlist-exists.ts` with the following content:
1000
1001 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1740071251/Medusa%20Resources/wishlist-29_bq6kcn.jpg)
1002
1003 ```ts title="src/workflows/steps/validate-wishlist-exists.ts"
1004 import { MedusaError } from "@medusajs/framework/utils"
1005 import { createStep } from "@medusajs/framework/workflows-sdk"
1006 import { InferTypeOf } from "@medusajs/framework/types"
1007 import { Wishlist } from "../../modules/wishlist/models/wishlist"
1008
1009 type Input = {
1010 wishlists?: InferTypeOf<typeof Wishlist>[]
1011 }
1012
1013 export const validateWishlistExistsStep = createStep(
1014 "validate-wishlist-exists",
1015 async (input: Input) => {
1016 if (!input.wishlists?.length) {
1017 throw new MedusaError(
1018 MedusaError.Types.NOT_FOUND,
1019 "No wishlist found for this customer"
1020 )
1021 }
1022 }
1023 )
1024 ```
1025
1026 This step receives an array of wishlists and throws an error if it's empty. You'll use this to stop the workflow's execution if the customer doesn't have a wishlist.
1027
1028 #### validateWishlistSalesChannelStep
1029
1030 The third step in the workflow validates that the wishlist belongs to the sales channel specified in the input.
1031
1032 To create the step, create the file `src/workflows/steps/validate-wishlist-sales-channel.ts` with the following content:
1033
1034 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737470093/Medusa%20Resources/wishlist-13_nn924e.jpg)
1035
1036 ```ts title="src/workflows/steps/validate-wishlist-sales-channel.ts"
1037 import { createStep } from "@medusajs/framework/workflows-sdk"
1038 import { InferTypeOf } from "@medusajs/framework/types"
1039 import { Wishlist } from "../../modules/wishlist/models/wishlist"
1040 import { MedusaError } from "@medusajs/framework/utils"
1041
1042 type ValidateWishlistSalesChannelStepInput = {
1043 wishlist: InferTypeOf<typeof Wishlist>
1044 sales_channel_id: string
1045 }
1046
1047 export const validateWishlistSalesChannelStep = createStep(
1048 "validate-wishlist-sales-channel",
1049 async (input: ValidateWishlistSalesChannelStepInput, { container }) => {
1050 const { wishlist, sales_channel_id } = input
1051
1052 if (wishlist.sales_channel_id !== sales_channel_id) {
1053 throw new MedusaError(
1054 MedusaError.Types.NOT_ALLOWED,
1055 "Wishlist does not belong to the current sales channel"
1056 )
1057 }
1058 }
1059 )
1060 ```
1061
1062 This step receives the wishlist object and the sales channel ID as input. In the step function, if the wishlist's sales channel ID doesn't match the sales channel ID in the input, you throw an error.
1063
1064 <Note>
1065
1066 To represent a data model in a type, use the [InferTypeOf](!docs!/learn/fundamentals/data-models/infer-type) utility.
1067
1068 </Note>
1069
1070 #### validateVariantWishlistStep
1071
1072 The next step in the workflow validates that the specified variant is not already in the wishlist.
1073
1074 Create the file `src/workflows/steps/validate-variant-wishlist.ts` with the following content:
1075
1076 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737470156/Medusa%20Resources/wishlist-14_ckoesz.jpg)
1077
1078 export const validateVariantWishlistHighlights = [
1079 ["23", "isInWishlist", "Check whether the variant is already in the wishlist."],
1080 ["38", "graph", "Retrieve the variant's details along with the sales channels that its product is available in."],
1081 ["50", "variantInSalesChannel", "Throw an error if the variant isn't in the wishlist's sales channel."]
1082 ]
1083
1084 ```ts title="src/workflows/steps/validate-variant-wishlist.ts" highlights={validateVariantWishlistHighlights}
1085 import { InferTypeOf } from "@medusajs/framework/types"
1086 import { Wishlist } from "../../modules/wishlist/models/wishlist"
1087 import { createStep } from "@medusajs/framework/workflows-sdk"
1088 import {
1089 MedusaError,
1090 ContainerRegistrationKeys,
1091 } from "@medusajs/framework/utils"
1092
1093 type ValidateVariantWishlistStepInput = {
1094 variant_id: string
1095 sales_channel_id: string
1096 wishlist: InferTypeOf<typeof Wishlist>
1097 }
1098
1099 export const validateVariantWishlistStep = createStep(
1100 "validate-variant-in-wishlist",
1101 async ({
1102 variant_id,
1103 sales_channel_id,
1104 wishlist,
1105 }: ValidateVariantWishlistStepInput, { container }) => {
1106 // validate whether variant is in wishlist
1107 const isInWishlist = wishlist.items?.some(
1108 (item) => item.product_variant_id === variant_id
1109 )
1110
1111 if (isInWishlist) {
1112 throw new MedusaError(
1113 MedusaError.Types.INVALID_DATA,
1114 "Variant is already in wishlist"
1115 )
1116 }
1117
1118 // validate that the variant is available in the specified sales channel
1119 const query = container.resolve(
1120 ContainerRegistrationKeys.QUERY
1121 )
1122 const { data } = await query.graph({
1123 entity: "variant",
1124 fields: ["product.sales_channels.*"],
1125 filters: {
1126 id: variant_id,
1127 },
1128 })
1129
1130 const variantInSalesChannel = data[0].product.sales_channels.some(
1131 (sc) => sc.id === sales_channel_id
1132 )
1133
1134 if (!variantInSalesChannel) {
1135 throw new MedusaError(
1136 MedusaError.Types.INVALID_DATA,
1137 "Variant is not available in the specified sales channel"
1138 )
1139 }
1140 }
1141 )
1142 ```
1143
1144 This step receives the variant ID, sales channel ID, and wishlist object as input. In the step function, you throw an error if:
1145
1146 - The variant is already in the wishlist.
1147 - The variant is not available in the specified sales channel. You use Query to retrieve the sales channels that the variant's product is available in.
1148
1149 #### createWishlistItemStep
1150
1151 The fifth step in the workflow creates a wishlist item for the specified variant in the wishlist.
1152
1153 Create the file `src/workflows/steps/create-wishlist-item.ts` with the following content:
1154
1155 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737470302/Medusa%20Resources/wishlist-15_oc696x.jpg)
1156
1157 export const createWishlistItemStepHighlights = [
1158 ["16", "createWishlistItems", "Create the wishlist item."],
1159 ["27", "deleteWishlistItems", "Delete the wishlist item if an error occurs in the workflow."]
1160 ]
1161
1162 ```ts title="src/workflows/steps/create-wishlist-item.ts" highlights={createWishlistItemStepHighlights}
1163 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1164 import WishlistModuleService from "../../modules/wishlist/service"
1165 import { WISHLIST_MODULE } from "../../modules/wishlist"
1166
1167 type CreateWishlistItemStepInput = {
1168 wishlist_id: string
1169 product_variant_id: string
1170 }
1171
1172 export const createWishlistItemStep = createStep(
1173 "create-wishlist-item",
1174 async (input: CreateWishlistItemStepInput, { container }) => {
1175 const wishlistModuleService: WishlistModuleService =
1176 container.resolve(WISHLIST_MODULE)
1177
1178 const item = await wishlistModuleService.createWishlistItems(input)
1179
1180 return new StepResponse(item, item.id)
1181 },
1182 async (id, { container }) => {
1183 if (!id) {
1184 return
1185 }
1186 const wishlistModuleService: WishlistModuleService =
1187 container.resolve(WISHLIST_MODULE)
1188
1189 await wishlistModuleService.deleteWishlistItems(id)
1190 }
1191 )
1192 ```
1193
1194 This step receives the wishlist ID and the variant ID as input. In the step function, you resolve the Wishlist Module's service from the container and use its generated `createWishlistItems` method to create the wishlist item, passing it the input as a parameter.
1195
1196 You return the created wishlist item and pass the item's ID to the compensation function. In the compensation function, you resolve the Wishlist Module's service from the container and use its generated `deleteWishlistItems` method to delete the wishlist item if an error occurs in the workflow.
1197
1198 #### Add Item to Wishlist Workflow
1199
1200 You can now add the `createWishlistItemWorkflow` to the plugin. Create the file `src/workflows/create-wishlist-item.ts` with the following content:
1201
1202 ![Directory structure after adding the workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737470660/Medusa%20Resources/wishlist-16_ovujwp.jpg)
1203
1204 export const createWishlistItemWorkflowHighlights = [
1205 ["17", "useQueryGraphStep", "Retrieve the wishlist of the specified customer."],
1206 ["25", "validateWishlistExistsStep", "Validate that the customer has a wishlist."],
1207 ["29", "validateWishlistSalesChannelStep", "Validate that the wishlist belongs to the specified sales channel."],
1208 ["35", "validateVariantWishlistStep", "Validate that the specified variant is not already in the wishlist."],
1209 ["41", "createWishlistItemStep", "Create the wishlist item."],
1210 ["47", "useQueryGraphStep", "Retrieve the wishlist again with the new item added."],
1211 ["56", "wishlist", "Return the wishlist with the new item."]
1212 ]
1213
1214 ```ts title="src/workflows/create-wishlist-item.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" highlights={createWishlistItemWorkflowHighlights}
1215 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
1216 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1217 import { validateWishlistSalesChannelStep } from "./steps/validate-wishlist-sales-channel"
1218 import { createWishlistItemStep } from "./steps/create-wishlist-item"
1219 import { validateVariantWishlistStep } from "./steps/validate-variant-wishlist"
1220 import { validateWishlistExistsStep } from "./steps/validate-wishlist-exists"
1221
1222 type CreateWishlistItemWorkflowInput = {
1223 variant_id: string
1224 customer_id: string
1225 sales_channel_id: string
1226 }
1227
1228 export const createWishlistItemWorkflow = createWorkflow(
1229 "create-wishlist-item",
1230 (input: CreateWishlistItemWorkflowInput) => {
1231 const { data: wishlists } = useQueryGraphStep({
1232 entity: "wishlist",
1233 fields: ["*", "items.*"],
1234 filters: {
1235 customer_id: input.customer_id,
1236 },
1237 })
1238
1239 validateWishlistExistsStep({
1240 wishlists,
1241 })
1242
1243 validateWishlistSalesChannelStep({
1244 wishlist: wishlists[0],
1245 sales_channel_id: input.sales_channel_id,
1246 })
1247
1248
1249 validateVariantWishlistStep({
1250 variant_id: input.variant_id,
1251 sales_channel_id: input.sales_channel_id,
1252 wishlist: wishlists[0],
1253 })
1254
1255 createWishlistItemStep({
1256 product_variant_id: input.variant_id,
1257 wishlist_id: wishlists[0].id,
1258 })
1259
1260 // refetch wishlist
1261 const { data: updatedWishlists } = useQueryGraphStep({
1262 entity: "wishlist",
1263 fields: ["*", "items.*", "items.product_variant.*"],
1264 filters: {
1265 id: wishlists[0].id,
1266 },
1267 }).config({ name: "refetch-wishlist" })
1268
1269 return new WorkflowResponse({
1270 wishlist: updatedWishlists[0],
1271 })
1272 }
1273 )
1274 ```
1275
1276 You create a `createWishlistItemWorkflow`. In the workflow, you:
1277
1278 - Use the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) to retrieve the wishlist of a customer. Notice that you pass the link definition between a wishlist and a customer as an entry point to Query. This allows you to filter the wishlist by the customer ID.
1279 - Use the `validateWishlistSalesChannelStep` step to validate that the wishlist belongs to the sales channel specified in the input.
1280 - Use the `validateVariantWishlistStep` step to validate that the variant specified in the input is not already in the wishlist.
1281 - Use the `createWishlistItemStep` step to create the wishlist item.
1282 - Use the `useQueryGraphStep` again to retrieve the wishlist with the new item added.
1283
1284 You return the wishlist with its items.
1285
1286 ### Add Item to Wishlist API Route
1287
1288 You'll now create an API route that executes the `createWishlistItemWorkflow` to add an item to a wishlist.
1289
1290 Create the file `src/api/store/customers/me/wishlists/items/route.ts` with the following content:
1291
1292 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737470985/Medusa%20Resources/wishlist-17_zmqk6c.jpg)
1293
1294 ```ts title="src/api/store/customers/me/wishlists/items/route.ts"
1295 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
1296 import { createWishlistItemWorkflow } from "../../../../../../workflows/create-wishlist-item"
1297 import { MedusaError } from "@medusajs/framework/utils"
1298
1299 type PostStoreCreateWishlistItemType = {
1300 variant_id: string
1301 }
1302
1303 export async function POST(
1304 req: AuthenticatedMedusaRequest<PostStoreCreateWishlistItemType>,
1305 res: MedusaResponse
1306 ) {
1307 if (!req.publishable_key_context?.sales_channel_ids.length) {
1308 throw new MedusaError(
1309 MedusaError.Types.INVALID_DATA,
1310 "At least one sales channel ID is required to be associated with the publishable API key in the request header."
1311 )
1312 }
1313 const { result } = await createWishlistItemWorkflow(req.scope)
1314 .run({
1315 input: {
1316 variant_id: req.validatedBody.variant_id,
1317 customer_id: req.auth_context.actor_id,
1318 sales_channel_id: req.publishable_key_context?.sales_channel_ids[0],
1319 },
1320 })
1321
1322 res.json({
1323 wishlist: result.wishlist,
1324 })
1325 }
1326 ```
1327
1328 This route exposes a `POST` endpoint at `/store/customers/me/wishlists/items`. Notice that the `AuthenticatedMedusaRequest` accepts a type parameter indicating the type of the accepted request body. In this case, the request body must have a `variant_id` property, indicating the ID of the variant to add to the wishlist.
1329
1330 In the route handler function, you execute the `createWishlistItemWorkflow` workflow, passing the authenticated customer ID, the variant ID, and the sales channel ID as input. You return in the response the updated wishlist.
1331
1332 ### Add Validation Schema
1333
1334 To ensure that a variant ID is passed in the body of requests sent to this API route, you'll define a validation schema for the request body.
1335
1336 In Medusa, you create validation schemas using [Zod](https://zod.dev/) in a TypeScript file under the `src/api` directory. So, create the file `src/api/store/customers/me/wishlists/items/validators.ts` with the following content:
1337
1338 ![Directory structure after adding the validation schema file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737471383/Medusa%20Resources/wishlist-18_hj9iom.jpg)
1339
1340 <Note>
1341
1342 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
1343
1344 </Note>
1345
1346 ```ts title="src/api/store/customers/me/wishlists/items/validators.ts"
1347 import { z } from "@medusajs/framework/zod"
1348
1349 export const PostStoreCreateWishlistItem = z.object({
1350 variant_id: z.string(),
1351 })
1352 ```
1353
1354 You create an object schema with a `variant_id` property of type `string`.
1355
1356 <Note>
1357
1358 Learn more about creating schemas in [Zod's documentation](https://zod.dev/).
1359
1360 </Note>
1361
1362 You can now replace the `PostStoreCreateWishlistItemType` type in `src/api/store/customers/me/wishlists/items/route.ts` with the following:
1363
1364 <Note>
1365
1366 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
1367
1368 </Note>
1369
1370 ```ts title="src/api/store/customers/me/wishlists/items/route.ts"
1371 // ...
1372 import { z } from "@medusajs/framework/zod"
1373 import { PostStoreCreateWishlistItem } from "./validators"
1374
1375 type PostStoreCreateWishlistItemType = z.infer<
1376 typeof PostStoreCreateWishlistItem
1377 >
1378 ```
1379
1380 Finally, to use the schema for validation, you need to apply the `validateAndTransformBody` middleware on the `/store/customers/me/wishlists/items` route. A middleware is a function executed before the API route when a request is sent to it.
1381
1382 The `validateAndTransformBody` middleware is available out-of-the-box in Medusa, allowing you to validate and transform the request body using a Zod schema.
1383
1384 <Note>
1385
1386 Learn more about middlewares in [this documentation](!docs!/learn/fundamentals/api-routes/middlewares).
1387
1388 </Note>
1389
1390 To apply the middleware, create the file `src/api/middlewares.ts` with the following content:
1391
1392 ![Directory structure after adding the middleware file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737471615/Medusa%20Resources/wishlist-19_ryyzdk.jpg)
1393
1394 ```ts title="src/api/middlewares.ts"
1395 import {
1396 defineMiddlewares,
1397 validateAndTransformBody,
1398 } from "@medusajs/framework/http"
1399 import {
1400 PostStoreCreateWishlistItem,
1401 } from "./store/customers/me/wishlists/items/validators"
1402
1403 export default defineMiddlewares({
1404 routes: [
1405 {
1406 matcher: "/store/customers/me/wishlists/items",
1407 method: "POST",
1408 middlewares: [
1409 validateAndTransformBody(PostStoreCreateWishlistItem),
1410 ],
1411 },
1412 ],
1413 })
1414 ```
1415
1416 In this file, you export the middlewares definition using `defineMiddlewares` from the Medusa Framework. This function accepts an object having a `routes` property, which is an array of middleware configurations to apply on routes.
1417
1418 You pass in the `routes` array an object having the following properties:
1419
1420 - `matcher`: The route to apply the middleware on.
1421 - `method`: The HTTP method to apply the middleware on for the specified API route.
1422 - `middlewares`: An array of the middlewares to apply. You apply the following middleware:
1423 - `validateAndTransformBody`: A middleware to ensure the received request body is valid against the Zod schema you defined earlier.
1424
1425 Any request sent to `/store/customers/me/wishlists/items` will now automatically fail if its body parameters don't match the `PostStoreCreateWishlistItem` validation schema.
1426
1427 ### Test API Route
1428
1429 Start the Medusa application to test out the API route.
1430
1431 <Note>
1432
1433 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
1434
1435 </Note>
1436
1437 #### Retrieve Variant ID
1438
1439 To retrieve an ID of a variant to add to the wishlist, send a `GET` request to the `/store/products` API route:
1440
1441 ```bash
1442 curl 'localhost:9000/store/products' \
1443 --header 'x-publishable-api-key: {api_key}'
1444 ```
1445
1446 Make sure to replace `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1447
1448 The response will contain a list of products. You can use the `id` of a product's variant to add to the wishlist.
1449
1450 #### Add Variant to Wishlist
1451
1452 Then, send a `POST` request to the `/store/customers/me/wishlists/items` API route to add the variant to the wishlist:
1453
1454 ```bash
1455 curl -X POST 'localhost:9000/store/customers/me/wishlists/items' \
1456 --header 'Content-Type: application/json' \
1457 --header 'x-publishable-api-key: {api_key}' \
1458 --header 'Authorization: Bearer {token}' \
1459 --data-raw '{
1460 "variant_id": "{variant_id}"
1461 }'
1462 ```
1463
1464 Make sure to replace:
1465
1466 - `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1467 - `{token}` with the authenticated customer token, as explained in [a previous section](#retrieve-authenticated-customer-token).
1468 - `{variant_id}` with the ID of the variant you retrieved from the `/store/products` API route.
1469
1470 You'll receive in the response the updated wishlist with the added item.
1471
1472 ---
1473
1474 ## Step 10: Remove Item from Wishlist API Route
1475
1476 In this step, you'll add the functionality to remove an item from a wishlist. You'll first define a workflow that implements this functionality, then create an API route that executes the workflow.
1477
1478 ### Remove Item from Wishlist Workflow
1479
1480 The workflow to remove an item from a wishlist has the following steps:
1481
1482 <WorkflowDiagram
1483 workflow={{
1484 name: "deleteWishlistItemWorkflow",
1485 steps: [
1486 {
1487 type: "step",
1488 name: "useQueryGraphStep",
1489 description: "Retrieve the wishlist of a customer.",
1490 depth: 1,
1491 link: "/references/helper-steps/useQueryGraphStep"
1492 },
1493 {
1494 type: "step",
1495 name: "validateWishlistExistsStep",
1496 description: "Validate that the customer's wishlist exists.",
1497 depth: 1
1498 },
1499 {
1500 type: "step",
1501 name: "validateItemInWishlistStep",
1502 description: "Validate that the item is in the customer's wishlist.",
1503 depth: 1
1504 },
1505 {
1506 type: "step",
1507 name: "deleteWishlistItemStep",
1508 description: "Delete the wishlist item.",
1509 depth: 1
1510 },
1511 {
1512 type: "step",
1513 name: "useQueryGraphStep",
1514 description: "Retrieve the wishlist again with the item removed.",
1515 depth: 1,
1516 link: "/references/helper-steps/useQueryGraphStep"
1517 },
1518 ]
1519 }}
1520 hideLegend
1521 />
1522
1523 The `useQueryGraphStep` is from Medusa's workflows package, and you implemented the `validateWishlistExistsStep` [previously](#validatewishlistexistsstep) . So, you'll only implement the other steps.
1524
1525 #### validateItemInWishlistStep
1526
1527 The second step of the workflow validates that the item to remove is in the authenticated customer's wishlist.
1528
1529 To create the step, create the file `src/workflows/steps/validate-item-in-wishlist.ts` with the following content:
1530
1531 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737474621/Medusa%20Resources/wishlist-20_jcwrtf.jpg)
1532
1533 ```ts title="src/workflows/steps/validate-item-in-wishlist.ts"
1534 import { InferTypeOf } from "@medusajs/framework/types"
1535 import { Wishlist } from "../../modules/wishlist/models/wishlist"
1536 import { createStep } from "@medusajs/framework/workflows-sdk"
1537 import { MedusaError } from "@medusajs/framework/utils"
1538
1539 type ValidateItemInWishlistStepInput = {
1540 wishlist: InferTypeOf<typeof Wishlist>
1541 wishlist_item_id: string
1542 }
1543
1544 export const validateItemInWishlistStep = createStep(
1545 "validate-item-in-wishlist",
1546 async ({
1547 wishlist,
1548 wishlist_item_id,
1549 }: ValidateItemInWishlistStepInput, { container }) => {
1550 const item = wishlist.items.find((item) => item.id === wishlist_item_id)
1551
1552 if (!item) {
1553 throw new MedusaError(
1554 MedusaError.Types.INVALID_DATA,
1555 "Item does not exist in customer's wishlist"
1556 )
1557 }
1558 }
1559 )
1560 ```
1561
1562 This step receives the wishlist object and the wishlist item ID as input. In the step function, you find the item in the wishlist by its ID. If the item doesn't exist, you throw an error.
1563
1564 #### deleteWishlistItemStep
1565
1566 The third step of the workflow deletes the item from the wishlist.
1567
1568 Create the file `src/workflows/steps/delete-wishlist-item.ts` with the following content:
1569
1570 ![Directory structure after adding the step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737474703/Medusa%20Resources/wishlist-21_e50lrg.jpg)
1571
1572 ```ts title="src/workflows/steps/delete-wishlist-item.ts"
1573 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1574 import WishlistModuleService from "../../modules/wishlist/service"
1575 import { WISHLIST_MODULE } from "../../modules/wishlist"
1576
1577 type DeleteWishlistItemStepInput = {
1578 wishlist_item_id: string
1579 }
1580
1581 export const deleteWishlistItemStep = createStep(
1582 "delete-wishlist-item",
1583 async ({ wishlist_item_id }: DeleteWishlistItemStepInput, { container }) => {
1584 const wishlistModuleService: WishlistModuleService =
1585 container.resolve(WISHLIST_MODULE)
1586
1587 await wishlistModuleService.softDeleteWishlistItems(wishlist_item_id)
1588
1589 return new StepResponse(void 0, wishlist_item_id)
1590 },
1591 async (wishlistItemId, { container }) => {
1592 const wishlistModuleService: WishlistModuleService =
1593 container.resolve(WISHLIST_MODULE)
1594
1595 await wishlistModuleService.restoreWishlistItems([wishlistItemId])
1596 }
1597 )
1598 ```
1599
1600 This step receives the wishlist item ID as input. In the step function, you resolve the Wishlist Module's service from the container and use its generated `softDeleteWishlistItems` method to delete the wishlist item.
1601
1602 You pass the deleted wishlist item ID to the compensation function. In the compensation function, you resolve the Wishlist Module's service from the container and use its generated `restoreWishlistItems` method to restore the wishlist item if an error occurs in the workflow.
1603
1604 <Note>
1605
1606 Learn more about the [softDelete](../../../service-factory-reference/methods/soft-delete/page.mdx) and [restore](../../../service-factory-reference/methods/restore/page.mdx) generated methods.
1607
1608 </Note>
1609
1610 #### Remove Item from Wishlist Workflow
1611
1612 You can now add the `deleteWishlistItemWorkflow` to the plugin. Create the file `src/workflows/delete-wishlist-item.ts` with the following content:
1613
1614 ![Directory structure after adding the workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737474872/Medusa%20Resources/wishlist-22_wt1g36.jpg)
1615
1616 export const deleteWishlistItemWorkflowHighlights = [
1617 ["15", "useQueryGraphStep", "Retrieve the wishlist of a customer."],
1618 ["23", "validateWishlistExistsStep", "Validate that the customer has a wishlist."],
1619 ["27", "validateItemInWishlistStep", "Validate that the item is in the customer's wishlist."],
1620 ["32", "deleteWishlistItemStep", "Delete the wishlist item."],
1621 ["35", "useQueryGraphStep", "Retrieve the wishlist again with the item removed."],
1622 ["44", "wishlist", "Return the wishlist without the removed item."]
1623 ]
1624
1625 ```ts title="src/workflows/delete-wishlist-item.ts" highlights={deleteWishlistItemWorkflowHighlights}
1626 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
1627 import { deleteWishlistItemStep } from "./steps/delete-wishlist-item"
1628 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1629 import { validateItemInWishlistStep } from "./steps/validate-item-in-wishlist"
1630 import { validateWishlistExistsStep } from "./steps/validate-wishlist-exists"
1631
1632 type DeleteWishlistItemWorkflowInput = {
1633 wishlist_item_id: string
1634 customer_id: string
1635 }
1636
1637 export const deleteWishlistItemWorkflow = createWorkflow(
1638 "delete-wishlist-item",
1639 (input: DeleteWishlistItemWorkflowInput) => {
1640 const { data: wishlists } = useQueryGraphStep({
1641 entity: "wishlist",
1642 fields: ["*", "items.*"],
1643 filters: {
1644 customer_id: input.customer_id,
1645 },
1646 })
1647
1648 validateWishlistExistsStep({
1649 wishlists,
1650 })
1651
1652 validateItemInWishlistStep({
1653 wishlist: wishlists[0],
1654 wishlist_item_id: input.wishlist_item_id,
1655 })
1656
1657 deleteWishlistItemStep(input)
1658
1659 // refetch wishlist
1660 const { data: updatedWishlists } = useQueryGraphStep({
1661 entity: "wishlist",
1662 fields: ["*", "items.*", "items.product_variant.*"],
1663 filters: {
1664 id: wishlists[0].id,
1665 },
1666 }).config({ name: "refetch-wishlist" })
1667
1668 return new WorkflowResponse({
1669 wishlist: updatedWishlists[0],
1670 })
1671 }
1672 )
1673 ```
1674
1675 You create a `deleteWishlistItemWorkflow`. In the workflow, you:
1676
1677 - Use the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) to retrieve the wishlist of a customer. Notice that you pass the link definition between a wishlist and a customer as an entry point to Query. This allows you to filter the wishlist by the customer ID.
1678 - Use the `validateItemInWishlistStep` step to validate that the item to remove is in the customer's wishlist.
1679 - Use the `deleteWishlistItemStep` step to delete the item from the wishlist.
1680 - Use the `useQueryGraphStep` again to retrieve the wishlist with the item removed.
1681
1682 You return the wishlist without the removed item.
1683
1684 ### Remove Item from Wishlist API Route
1685
1686 You'll now create an API route that executes the `deleteWishlistItemWorkflow` to remove an item from a wishlist.
1687
1688 Create the file `src/api/store/customers/me/wishlists/items/[id]/route.ts` with the following content:
1689
1690 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737475074/Medusa%20Resources/wishlist-23_qatcia.jpg)
1691
1692 ```ts title="src/api/store/customers/me/wishlists/items/[id]/route.ts"
1693 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
1694 import { deleteWishlistItemWorkflow } from "../../../../../../../workflows/delete-wishlist-item"
1695
1696 export async function DELETE(
1697 req: AuthenticatedMedusaRequest,
1698 res: MedusaResponse
1699 ) {
1700 const { result } = await deleteWishlistItemWorkflow(req.scope)
1701 .run({
1702 input: {
1703 wishlist_item_id: req.params.id,
1704 customer_id: req.auth_context.actor_id,
1705 },
1706 })
1707
1708 res.json({
1709 wishlist: result.wishlist,
1710 })
1711 }
1712 ```
1713
1714 This route exposes a `DELETE` endpoint at `/store/customers/me/wishlists/items/:id`. The `:id` parameter in the route path represents the ID of the wishlist item to remove.
1715
1716 In the route handler function, you execute the `deleteWishlistItemWorkflow` workflow, passing the authenticated customer ID and the wishlist item ID as input. You return in the response the updated wishlist.
1717
1718 ### Test API Route
1719
1720 Start the Medusa application to test out the API route.
1721
1722 <Note>
1723
1724 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
1725
1726 </Note>
1727
1728 #### Retrieve Wishlist Item ID
1729
1730 To retrieve an ID of a wishlist item to remove, send a `GET` request to the `/store/customers/me/wishlists` API route:
1731
1732 ```bash
1733 curl 'localhost:9000/store/customers/me/wishlists' \
1734 --header 'x-publishable-api-key: {api_key}' \
1735 --header 'Authorization: Bearer {token}'
1736 ```
1737
1738 Make sure to replace:
1739
1740 - `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1741 - `{token}` with the authenticated customer token, as explained in [a previous section](#retrieve-authenticated-customer-token).
1742
1743 The response will contain the wishlist of the authenticated customer. You can use the `id` of an item in the wishlist to remove.
1744
1745 #### Remove Item from Wishlist
1746
1747 Then, send a `DELETE` request to the `/store/customers/me/wishlists/items/:id` API route to remove the item from the wishlist:
1748
1749 ```bash
1750 curl -X DELETE 'localhost:9000/store/customers/me/wishlists/items/{item_id}' \
1751 --header 'x-publishable-api-key: {api_key}' \
1752 --header 'Authorization: Bearer {token}'
1753 ```
1754
1755 Make sure to replace:
1756
1757 - `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1758 - `{token}` with the authenticated customer token, as explained in [a previous section](#retrieve-authenticated-customer-token).
1759 - `{item_id}` with the ID of the item you retrieved from the `/store/customers/me/wishlists` API route.
1760
1761 You'll receive in the response the updated wishlist without the removed item.
1762
1763 ---
1764
1765 ## Step 11: Share Wishlist API Route
1766
1767 In this step, you'll add the functionality to allow customers to share their wishlist with others. The route will return a token that can be passed to another API route that you'll create in the next step to retrieve the shared wishlist.
1768
1769 To create the token and decode it later, you'll use the [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken) package. So, run the following command in the plugin project to install the package:
1770
1771 ```bash npm2yarn badgeLabel="Plugin project" badgeColor="orange"
1772 npm install jsonwebtoken
1773 ```
1774
1775 Then, to create the API route, create the file `src/api/store/customers/me/wishlists/share/route.ts` with the following content:
1776
1777 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737475331/Medusa%20Resources/wishlist-24_tiwjpr.jpg)
1778
1779 ```ts title="src/api/store/customers/me/wishlists/share/route.ts"
1780 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
1781 import {
1782 MedusaError,
1783 ContainerRegistrationKeys,
1784 } from "@medusajs/framework/utils"
1785 import jwt from "jsonwebtoken"
1786
1787 export async function POST(
1788 req: AuthenticatedMedusaRequest,
1789 res: MedusaResponse
1790 ) {
1791 if (!req.publishable_key_context?.sales_channel_ids.length) {
1792 throw new MedusaError(
1793 MedusaError.Types.INVALID_DATA,
1794 "At least one sales channel ID is required to be associated with the publishable API key in the request header."
1795 )
1796 }
1797
1798 const query = req.scope.resolve(
1799 ContainerRegistrationKeys.QUERY
1800 )
1801
1802 const { data } = await query.graph({
1803 entity: "wishlist",
1804 fields: ["*"],
1805 filters: {
1806 customer_id: req.auth_context.actor_id,
1807 },
1808 })
1809
1810 if (!data.length) {
1811 throw new MedusaError(
1812 MedusaError.Types.NOT_FOUND,
1813 "No wishlist found for customer"
1814 )
1815 }
1816
1817 if (data[0].sales_channel_id !== req.publishable_key_context.sales_channel_ids[0]) {
1818 throw new MedusaError(
1819 MedusaError.Types.INVALID_DATA,
1820 "Wishlist does not belong to the specified sales channel"
1821 )
1822 }
1823
1824 // TODO generate the token
1825 }
1826 ```
1827
1828 This route exposes a `POST` endpoint at `/store/customers/me/wishlists/share`. In the route handler function, you use Query to retrieve the wishlist of the authenticated customer. If the customer doesn't have a wishlist, or the wishlist doesn't belong to the sales channel specified in the request's publishable API key, you throw an error.
1829
1830 You'll now generate a token that contains the wishlist ID. To do this, replace the `TODO` in the route handler function with the following:
1831
1832 ```ts title="src/api/store/customers/me/wishlists/share/route.ts"
1833 const { http } = req.scope.resolve(
1834 ContainerRegistrationKeys.CONFIG_MODULE
1835 ).projectConfig
1836
1837 const wishlistToken = jwt.sign({
1838 wishlist_id: data[0].id,
1839 }, http.jwtSecret!, {
1840 expiresIn: http.jwtExpiresIn,
1841 })
1842
1843 return res.json({
1844 token: wishlistToken,
1845 })
1846 ```
1847
1848 You first retrieve the [http Medusa configuration](!docs!/learn/configurations/medusa-config#http) which holds configurations related to JWT secrets and expiration times. You then use the `jsonwebtoken` package to sign a token containing the wishlist ID. You return the token in the response.
1849
1850 ### Test API Route
1851
1852 Start the Medusa application to test out the API route.
1853
1854 <Note>
1855
1856 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
1857
1858 </Note>
1859
1860 Then, send a `POST` request to the `/store/customers/me/wishlists/share` API route to generate a share token for the authenticated customer's wishlist:
1861
1862 ```bash
1863 curl -X POST 'localhost:9000/store/customers/me/wishlists/share' \
1864 --header 'x-publishable-api-key: {api_key}' \
1865 --header 'Authorization: Bearer {token}'
1866 ```
1867
1868 Make sure to replace:
1869
1870 - `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1871 - `{token}` with the authenticated customer token, as explained in [a previous section](#retrieve-authenticated-customer-token).
1872
1873 You'll receive in the response a token that you can pass to the next API route to retrieve the shared wishlist.
1874
1875 ---
1876
1877 ## Step 12: Retrieve Shared Wishlist API Route
1878
1879 In this step, you'll add an API route that retrieves a wishlist shared using a token returned by the `/store/customers/me/wishlists/share` API route.
1880
1881 Create the file `src/api/store/wishlists/[token]/route.ts` with the following content:
1882
1883 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737475795/Medusa%20Resources/wishlist-25_sodzsr.jpg)
1884
1885 ```ts title="src/api/store/wishlists/[token]/route.ts"
1886 import { MedusaResponse, MedusaStoreRequest } from "@medusajs/framework"
1887 import {
1888 MedusaError,
1889 ContainerRegistrationKeys,
1890 } from "@medusajs/framework/utils"
1891 import { decode, JwtPayload } from "jsonwebtoken"
1892
1893 export async function GET(
1894 req: MedusaStoreRequest,
1895 res: MedusaResponse
1896 ) {
1897 if (!req.publishable_key_context?.sales_channel_ids.length) {
1898 throw new MedusaError(
1899 MedusaError.Types.INVALID_DATA,
1900 "At least one sales channel ID is required to be associated with the publishable API key in the request header."
1901 )
1902 }
1903
1904 const decodedToken = decode(req.params.token) as JwtPayload
1905
1906 if (!decodedToken.wishlist_id) {
1907 throw new MedusaError(
1908 MedusaError.Types.INVALID_DATA,
1909 "Invalid token"
1910 )
1911 }
1912
1913 const query = req.scope.resolve(
1914 ContainerRegistrationKeys.QUERY
1915 )
1916
1917 const { data } = await query.graph({
1918 entity: "wishlist",
1919 fields: ["*", "items.*", "items.product_variant.*"],
1920 filters: {
1921 id: decodedToken.wishlist_id,
1922 },
1923 })
1924
1925 if (!data.length) {
1926 throw new MedusaError(
1927 MedusaError.Types.NOT_FOUND,
1928 "No wishlist found"
1929 )
1930 }
1931
1932 if (data[0].sales_channel_id !== req.publishable_key_context.sales_channel_ids[0]) {
1933 throw new MedusaError(
1934 MedusaError.Types.INVALID_DATA,
1935 "Wishlist does not belong to the request's sales channel"
1936 )
1937 }
1938
1939 res.json({
1940 wishlist: data[0],
1941 })
1942 }
1943 ```
1944
1945 This route exposes a `GET` endpoint at `/store/wishlists/:token`. The `:token` parameter in the route path represents the token generated by the `/store/customers/me/wishlists/share` API route.
1946
1947 In the route handler function, you decode the token to retrieve the wishlist ID. If the token is invalid, you throw an error.
1948
1949 Then, you use Query to retrieve the wishlist with the ID from the decoded token. If no wishlist is found or the wishlist doesn't belong to the sales channel ID of the current request, you throw an error.
1950
1951 You return in the response the shared wishlist.
1952
1953 ### Test API Route
1954
1955 Start the Medusa application to test out the API route.
1956
1957 <Note>
1958
1959 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
1960
1961 </Note>
1962
1963 Then, send a `GET` request to the `/store/wishlists/:token` API route to retrieve the shared wishlist:
1964
1965 ```bash
1966 curl 'localhost:9000/store/wishlists/{wishlist_token}' \
1967 --header 'x-publishable-api-key: {api_key}'
1968 ```
1969
1970 Make sure to replace:
1971
1972 - `{wishlist_token}` with the token you received from the `/store/customers/me/wishlists/share` API route.
1973 - `{api_key}` with the publishable API key you copied from the settings, as explained in [a previous section](#retrieve-publishable-api-key).
1974
1975 You'll receive in the response the shared wishlist.
1976
1977 ---
1978
1979 ## Step 13: Show Wishlist Count in Medusa Admin
1980
1981 In this step, you'll customize the Medusa Admin dashboard to show for each product the number of wishlists it's in.
1982
1983 The Medusa Admin dashboard's pages are customizable to insert widgets of custom content in pre-defined injection zones. You create these widgets as React components that allow admin users to perform custom actions.
1984
1985 <Note>
1986
1987 Learn more about widgets in [this documentation](!docs!/learn/fundamentals/admin/widgets).
1988
1989 </Note>
1990
1991 ### Add Method to Retrieve Wishlist Count
1992
1993 To retrieve the number of wishlists a product is in, you'll add a method to the `WishlistModuleService` that runs a query to retrieve distinct wishlist IDs containing a product variant.
1994
1995 In `src/modules/wishlist/service.ts`, add the following imports and method:
1996
1997 ```ts title="src/modules/wishlist/service.ts"
1998 // other imports...
1999 import { InjectManager } from "@medusajs/framework/utils"
2000 import { Context } from "@medusajs/framework/types"
2001 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
2002
2003 export default class WishlistModuleService extends MedusaService({
2004 Wishlist,
2005 WishlistItem,
2006 }) {
2007 @InjectManager()
2008 async getWishlistsOfVariants(
2009 variantIds: string[],
2010 @MedusaContext() context: Context<EntityManager> = {}
2011 ): Promise<number> {
2012 return (await context.manager?.createQueryBuilder("wishlist_item", "wi")
2013 .select(["wi.wishlist_id"], true)
2014 .where("wi.product_variant_id IN (?)", [variantIds])
2015 .execute())?.length || 0
2016 }
2017 }
2018 ```
2019
2020 To perform queries on the database in a method, add the `@InjectManager` decorator to the method. This will inject a [forked MikroORM entity manager](https://mikro-orm.io/docs/identity-map#forking-entity-manager) that you can use in your method.
2021
2022 Methods with the `@InjectManager` decorator accept as a last parameter a context object that has the `@MedusaContext` decorator. The entity manager is injected into the `manager` property of this parameter.
2023
2024 The method accepts an array of variant IDs as a parameter. In the method, you use the `createQueryBuilder` to construct a query, passing it the name of the `WishlistItem`'s table. You then select distinct `wishlist_id`s where the `product_variant_id` of the wishlist item is in the array of variant IDs.
2025
2026 You execute the query and return the number of distinct wishlist IDs containing the product variants. You'll use this method next.
2027
2028 ### Create Wishlist Count API Route
2029
2030 Before creating the widget, you'll create the API route that retrieves the number of wishlists a product is in.
2031
2032 Create the file `src/api/store/products/[id]/wishlist/route.ts` with the following content:
2033
2034 ![Directory structure after adding the route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737630927/Medusa%20Resources/wishlist-26_ervnfg.jpg)
2035
2036 export const wishlistCountRouteHighlights = [
2037 ["22", "graph", "Retrieve the product and its variants."],
2038 ["30", "", "If product doesn't exist, throw an error."],
2039 ["37", "count", "Retrieve the number of wishlists that the product is in."]
2040 ]
2041
2042 ```ts title="src/api/store/products/[id]/wishlist/route.ts" highlights={wishlistCountRouteHighlights}
2043 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
2044 import WishlistModuleService from "../../../../../modules/wishlist/service"
2045 import { WISHLIST_MODULE } from "../../../../../modules/wishlist"
2046 import {
2047 MedusaError,
2048 ContainerRegistrationKeys,
2049 } from "@medusajs/framework/utils"
2050
2051 export async function GET(
2052 req: MedusaRequest,
2053 res: MedusaResponse
2054 ) {
2055 const { id } = req.params
2056
2057 const query = req.scope.resolve(
2058 ContainerRegistrationKeys.QUERY
2059 )
2060 const wishlistModuleService: WishlistModuleService = req.scope.resolve(
2061 WISHLIST_MODULE
2062 )
2063
2064 const { data: [product] } = await query.graph({
2065 entity: "product",
2066 fields: ["variants.*"],
2067 filters: {
2068 id,
2069 },
2070 })
2071
2072 if (!product) {
2073 throw new MedusaError(
2074 MedusaError.Types.NOT_FOUND,
2075 `Product with id: ${id} was not found`
2076 )
2077 }
2078
2079 const count = await wishlistModuleService.getWishlistsOfVariants(
2080 product.variants.map((v) => v.id)
2081 )
2082
2083 res.json({
2084 count,
2085 })
2086 }
2087 ```
2088
2089 This route exposes a `GET` endpoint at `/store/products/:id/wishlist`. The `:id` parameter in the route path represents the ID of the product to retrieve the wishlist count for.
2090
2091 In the route handler function, you use Query to retrieve the product and its variants, and throw an error if the product doesn't exist.
2092
2093 Then, you resolve the `WishlistModuleService` from the Medusa Container and use its `getWishlistsOfVariants` method to retrieve the number of wishlists the product's variants are in. You return the count in the response.
2094
2095 You'll use this API route in the widget next.
2096
2097 ### Create Wishlist Count Widget
2098
2099 You'll now create the widget that will be shown on a product's page in the Medusa Admin.
2100
2101 In the widget, you'll send a request to the API route you created to retrieve the wishlist count for the product. To send the request, you'll use the [JS SDK](../../../js-sdk/page.mdx), which is a JavaScript library that simplifies sending requests to Medusa's API routes.
2102
2103 To initialize the JS SDK, create the file `src/admin/lib/sdk.ts` with the following content:
2104
2105 ![Directory structure after adding the SDK file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737631853/Medusa%20Resources/wishlist-27_pkzeaj.jpg)
2106
2107 ```ts title="src/admin/lib/sdk.ts"
2108 import Medusa from "@medusajs/js-sdk"
2109
2110 export const sdk = new Medusa({
2111 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
2112 debug: import.meta.env.DEV,
2113 auth: {
2114 type: "session",
2115 },
2116 })
2117 ```
2118
2119 You initialize an instance of the JS SDK, which you'll use in the widget to send requests.
2120
2121 <Note>
2122
2123 Learn more about the JS SDK and configuring it in [this documentation](../../../js-sdk/page.mdx).
2124
2125 </Note>
2126
2127 Then, to create the widget, create the file `src/admin/widgets/product-widget.tsx` with the following content:
2128
2129 ![Directory structure after adding the widget file](https://res.cloudinary.com/dza7lstvk/image/upload/v1737631988/Medusa%20Resources/wishlist-28_fx8rw7.jpg)
2130
2131 export const widgetHighlights = [
2132 ["10", "WishlistResponse", "Define the type of expected response."],
2133 ["14", "ProductWidget", "Define and export the widget's React component."],
2134 ["15", "data", "Receive the product's details as a prop."],
2135 ["17", "useQuery", "Retrieve the wishlist count from the API route."],
2136 ["29", "", "Display the count."],
2137 ["36", "config", "Export the widget's content."],
2138 ["37", "zone", "Inject the widget into a product's details page."]
2139 ]
2140
2141 ```tsx title="src/admin/widgets/product-widget.tsx" highlights={widgetHighlights}
2142 import { defineWidgetConfig } from "@medusajs/admin-sdk"
2143 import { Container, Heading, Text } from "@medusajs/ui"
2144 import { useQuery } from "@tanstack/react-query"
2145 import { sdk } from "../lib/sdk"
2146 import {
2147 DetailWidgetProps,
2148 AdminProduct,
2149 } from "@medusajs/framework/types"
2150
2151 type WishlistResponse = {
2152 count: number
2153 }
2154
2155 const ProductWidget = ({
2156 data: product,
2157 }: DetailWidgetProps<AdminProduct>) => {
2158 const { data, isLoading } = useQuery<WishlistResponse>({
2159 queryFn: () => sdk.client.fetch(`/admin/products/${product.id}/wishlist`),
2160 queryKey: [["products", product.id, "wishlist"]],
2161 })
2162
2163 return (
2164 <Container className="divide-y p-0">
2165 <div className="flex items-center justify-between px-6 py-4">
2166 <Heading level="h2">Wishlist</Heading>
2167 </div>
2168 <Text className="px-6 py-4">
2169 {isLoading ?
2170 "Loading..." : `This product is in ${data?.count} wishlist(s).`
2171 }
2172 </Text>
2173 </Container>
2174 )
2175 }
2176
2177 export const config = defineWidgetConfig({
2178 zone: "product.details",
2179 })
2180
2181 export default ProductWidget
2182 ```
2183
2184 A widget file must export a React component and a `config` object created with `defineWidgetConfig` from the Admin Extension SDK. In the `config` object, you specify the zone to inject the widget into in the `zone` property. This widget is injected into a product's page before any other sections.
2185
2186 <Note title="Tip">
2187
2188 Find all widget injection zones in [this reference](../../../admin-widget-injection-zones/page.mdx).
2189
2190 </Note>
2191
2192 Since the widget is injected into a product's details page, it receives the product's details as a `data` prop. In the widget, you use [Tanstack Query](https://tanstack.com/query/latest) to benefit from features like data caching and invalidation. You use the `useQuery` hook to send a request to the API route you created to retrieve the wishlist count for the product.
2193
2194 Finally, you display the widget's content using components from [Medusa UI](!ui!), allowing you to align the design of your widget with the Medusa Admin's design system.
2195
2196 ### Test it Out
2197
2198 To test it out, start the Medusa application.
2199
2200 <Note>
2201
2202 Make sure that `plugin:develop` is running in the plugin project to publish the changes to the local registry.
2203
2204 </Note>
2205
2206 Then:
2207
2208 1. open the Medusa Admin at `localhost:9000/app` and log in.
2209
2210 2. Click on Products in the sidebar, then choose a product from the table.
2211
2212 ![Click on the "Products" in the sidebar on the right, then choose a product from the table shown in the middle](https://res.cloudinary.com/dza7lstvk/image/upload/v1737632826/Medusa%20Resources/Screenshot_2025-01-23_at_1.46.29_PM_xjsn8s.png)
2213
2214 3. You should see the widget you created showing the number of wishlists the product is in at the end of the page.
2215
2216 ---
2217
2218 ## Next Steps
2219
2220 You've now implemented the wishlist functionality in a Medusa plugin. You can publish that plugin as explained in [this documentation](!docs!/learn/fundamentals/plugins/create#5-publish-plugin-to-npm) to NPM and install it in any Medusa application. This will allow you to re-use your plugin or share it with the community.
2221
2222 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
2223
2224 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).