diff --git a/packages/generated/client-types/src/lib/models/AdminPostProductsProductReq.ts b/packages/generated/client-types/src/lib/models/AdminPostProductsProductReq.ts index 8d45b02c06..8411f1ea81 100644 --- a/packages/generated/client-types/src/lib/models/AdminPostProductsProductReq.ts +++ b/packages/generated/client-types/src/lib/models/AdminPostProductsProductReq.ts @@ -21,11 +21,11 @@ export interface AdminPostProductsProductReq { */ discountable?: boolean /** - * An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL. + * An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL. */ images?: Array /** - * The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL. + * The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL. */ thumbnail?: string /** diff --git a/packages/generated/client-types/src/lib/models/AdminPostProductsReq.ts b/packages/generated/client-types/src/lib/models/AdminPostProductsReq.ts index d7fe43cf08..fd1ff73f1f 100644 --- a/packages/generated/client-types/src/lib/models/AdminPostProductsReq.ts +++ b/packages/generated/client-types/src/lib/models/AdminPostProductsReq.ts @@ -25,11 +25,11 @@ export interface AdminPostProductsReq { */ discountable?: boolean /** - * An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL. + * An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL. */ images?: Array /** - * The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL. + * The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL. */ thumbnail?: string /** diff --git a/packages/generated/client-types/src/lib/models/StorePostCustomersCustomerAcceptClaimReq.ts b/packages/generated/client-types/src/lib/models/StorePostCustomersCustomerAcceptClaimReq.ts index 4227cd4295..fc89eb5d0b 100644 --- a/packages/generated/client-types/src/lib/models/StorePostCustomersCustomerAcceptClaimReq.ts +++ b/packages/generated/client-types/src/lib/models/StorePostCustomersCustomerAcceptClaimReq.ts @@ -5,7 +5,7 @@ import { SetRelation, Merge } from "../core/ModelUtils" export interface StorePostCustomersCustomerAcceptClaimReq { /** - * The claim token generated by previous request to the Claim Order endpoint. + * The claim token generated by previous request to the Claim Order API Route. */ token: string } diff --git a/packages/generated/client-types/src/lib/models/StorePostReturnsReq.ts b/packages/generated/client-types/src/lib/models/StorePostReturnsReq.ts index 6f12442bab..eca9358ef8 100644 --- a/packages/generated/client-types/src/lib/models/StorePostReturnsReq.ts +++ b/packages/generated/client-types/src/lib/models/StorePostReturnsReq.ts @@ -21,7 +21,7 @@ export interface StorePostReturnsReq { */ quantity: number /** - * The ID of the return reason. Return reasons can be retrieved from the List Return Reasons endpoint. + * The ID of the return reason. Return reasons can be retrieved from the List Return Reasons API Route. */ reason_id?: string /** diff --git a/packages/generated/client-types/src/lib/models/StorePostSwapsReq.ts b/packages/generated/client-types/src/lib/models/StorePostSwapsReq.ts index 081d738b1b..fee2d717be 100644 --- a/packages/generated/client-types/src/lib/models/StorePostSwapsReq.ts +++ b/packages/generated/client-types/src/lib/models/StorePostSwapsReq.ts @@ -21,7 +21,7 @@ export interface StorePostSwapsReq { */ quantity: number /** - * The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons endpoint. + * The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons API Route. */ reason_id?: string /** diff --git a/packages/medusa/oas/admin.oas.base.yaml b/packages/medusa/oas/admin.oas.base.yaml index faecb1a2f3..a1a45644bc 100644 --- a/packages/medusa/oas/admin.oas.base.yaml +++ b/packages/medusa/oas/admin.oas.base.yaml @@ -9,10 +9,10 @@ tags: - name: Apps Oauth description: | Some plugins may require to authenticate with third-party services and store authentication details, such as the authentication token. To do that, they can create an Oauth provider within the plugin that handles the authentication. - The Apps Oauth endpoints allows admins to manage and generate token for an app using its oauth provider. + The Apps Oauth API Routes allows admins to manage and generate token for an app using its oauth provider. - name: Auth description: | - Authentication endpoints allow admin users to manage their session, such as login or log out. + Authentication API Routes allow admin users to manage their session, such as login or log out. When an admin user is logged in, the cookie header is set indicating the admin's login session. externalDocs: description: How to implement user profiles @@ -20,14 +20,14 @@ tags: - name: Batch Jobs description: | A batch job is a task that is performed by the Medusa backend asynchronusly. For example, the Import Product feature is implemented using batch jobs. - Batch Job endpoints allows admins to manage the batch jobs and their state. + Batch Job API Routes allows admins to manage the batch jobs and their state. externalDocs: description: How to import products url: https://docs.medusajs.com/modules/products/admin/import-products - name: Currencies description: | A store can use unlimited currencies, and each region must be associated with at least one currency. - Currencies are defined within the Medusa backend. Currency endpoints allow admins to list and update currencies. + Currencies are defined within the Medusa backend. Currency API Routes allow admins to list and update currencies. externalDocs: description: How to manage currencies url: https://docs.medusajs.com/modules/regions-and-currencies/admin/manage-currencies @@ -47,7 +47,7 @@ tags: - name: Discounts description: | Admins can create discounts with conditions and rules, providing them with advanced settings for variety of cases. - The Discount endpoints can be used to manage discounts, their conditions, resources, and more. + The Discount API Routes can be used to manage discounts, their conditions, resources, and more. externalDocs: description: How to manage discounts url: https://docs.medusajs.com/modules/discounts/admin/manage-discounts @@ -60,7 +60,7 @@ tags: - name: Gift Cards description: | Admins can create gift cards and send them directly to customers, specifying options like their balance, region, and more. - These gift cards are different than the saleable gift cards in a store, which are created and managed through Product endpoints. + These gift cards are different than the saleable gift cards in a store, which are created and managed through Product API Routes. externalDocs: description: How to manage gift cards url: https://docs.medusajs.com/modules/gift-cards/admin/manage-gift-cards#manage-custom-gift-cards @@ -134,14 +134,14 @@ tags: - name: Product Variants description: | Product variants are the actual salable item in your store. Each variant is a combination of the different option values available on the product. - Product variants can be managed through the Products endpoints. + Product variants can be managed through the Products API Routes. externalDocs: description: How to manage product variants url: https://docs.medusajs.com/modules/products/admin/manage-products#manage-product-variants - name: Publishable API Keys description: | Publishable API Keys can be used to scope Store API calls with an API key, determining what resources are retrieved when querying the API. - For example, a publishable API key can be associated with one or more sales channels. When it is passed in the header of a request to the List Product store endpoint, + For example, a publishable API key can be associated with one or more sales channels. When it is passed in the header of a request to the List Product store API Route, the sales channels are inferred from the key and only products associated with those sales channels are retrieved. Admins can manage publishable API keys and their associated resources. Currently, only Sales Channels are supported as a resource. externalDocs: @@ -222,7 +222,7 @@ tags: url: https://docs.medusajs.com/modules/taxes/admin/manage-tax-rates - name: Uploads description: | - The upload endpoints are used to upload any type of resources. For example, they can be used to upload CSV files that are used to import products into the store. + The upload API Routes are used to upload any type of resources. For example, they can be used to upload CSV files that are used to import products into the store. externalDocs: description: How to upload CSV file when importing a product. url: https://docs.medusajs.com/modules/products/admin/import-products#1-upload-csv-file diff --git a/packages/medusa/oas/store.oas.base.yaml b/packages/medusa/oas/store.oas.base.yaml index 05da562d4d..ee0a848f5c 100644 --- a/packages/medusa/oas/store.oas.base.yaml +++ b/packages/medusa/oas/store.oas.base.yaml @@ -8,7 +8,7 @@ info: tags: - name: Auth description: | - Authentication endpoints allow customers to manage their session, such as login or log out. + Authentication API Routes allow customers to manage their session, such as login or log out. When a customer is logged in, the cookie header is set indicating the customer's login session. externalDocs: description: How to implement customer profiles in your storefront @@ -29,14 +29,14 @@ tags: - name: Gift Cards description: | Customers can use gift cards during checkout to deduct the gift card's balance from the checkout total. - The Gift Card endpoints allow retrieving a gift card's details by its code. A gift card can be applied to a cart using the Carts endpoints. + The Gift Card API Routes allow retrieving a gift card's details by its code. A gift card can be applied to a cart using the Carts API Routes. externalDocs: description: How to use gift cards in a storefront url: https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards - name: Orders description: | Orders are purchases made by customers, typically through a storefront. - Orders are placed and created using the Carts endpoints. The Orders endpoints allow retrieving and claiming orders. + Orders are placed and created using the Carts API Routes. The Orders API Routes allow retrieving and claiming orders. externalDocs: description: How to retrieve order details in a storefront url: https://docs.medusajs.com/modules/orders/storefront/retrieve-order-details @@ -53,7 +53,7 @@ tags: - name: Products description: | Products are saleable items in a store. This also includes [saleable gift cards](https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards) in a store. - Using these endpoints, you can filter products by categories, collections, sales channels, and more. + Using these API Routes, you can filter products by categories, collections, sales channels, and more. externalDocs: description: How to show products in a storefront url: https://docs.medusajs.com/modules/products/storefront/show-products @@ -63,14 +63,14 @@ tags: - name: Product Categories description: | Products can be categoriezed into categories. A product can be associated more than one category. - Using these endpoints, you can list or retrieve a category's details and products. + Using these API Routes, you can list or retrieve a category's details and products. externalDocs: description: How to use product categories in a storefront url: https://docs.medusajs.com/modules/products/storefront/use-categories - name: Product Collections description: | A product collection is used to organize products for different purposes such as marketing or discount purposes. For example, you can create a Summer Collection. - Using these endpoints, you can list or retrieve a collection's details and products. + Using these API Routes, you can list or retrieve a collection's details and products. - name: Product Tags description: | Product tags are string values that can be used to filter products by. diff --git a/packages/medusa/src/api/routes/admin/auth/delete-session.ts b/packages/medusa/src/api/routes/admin/auth/delete-session.ts index de893b1e90..797c8d84d8 100644 --- a/packages/medusa/src/api/routes/admin/auth/delete-session.ts +++ b/packages/medusa/src/api/routes/admin/auth/delete-session.ts @@ -4,7 +4,7 @@ * summary: "User Logout" * x-authenticated: true * description: "Delete the current session for the logged in user. This will only work if you're using Cookie session for authentication. If the API token is still passed in the header, - * the user is still authorized to perform admin functionalities in other endpoints." + * the user is still authorized to perform admin functionalities in other API Routes." * x-codegen: * method: deleteSession * x-codeSamples: diff --git a/packages/medusa/src/api/routes/admin/batch/confirm-batch-job.ts b/packages/medusa/src/api/routes/admin/batch/confirm-batch-job.ts index 8d356e6385..19610b2681 100644 --- a/packages/medusa/src/api/routes/admin/batch/confirm-batch-job.ts +++ b/packages/medusa/src/api/routes/admin/batch/confirm-batch-job.ts @@ -5,7 +5,7 @@ import { EntityManager } from "typeorm" * @oas [post] /admin/batch-jobs/{id}/confirm * operationId: "PostBatchJobsBatchJobConfirmProcessing" * summary: "Confirm a Batch Job" - * description: "When a batch job is created, it is not executed automatically if `dry_run` is set to `true`. This endpoint confirms that the batch job should be executed." + * description: "When a batch job is created, it is not executed automatically if `dry_run` is set to `true`. This API Route confirms that the batch job should be executed." * x-authenticated: true * parameters: * - (path) id=* {string} The ID of the batch job. diff --git a/packages/medusa/src/api/routes/admin/batch/create-batch-job.ts b/packages/medusa/src/api/routes/admin/batch/create-batch-job.ts index a9fbe56043..69ebc3201c 100644 --- a/packages/medusa/src/api/routes/admin/batch/create-batch-job.ts +++ b/packages/medusa/src/api/routes/admin/batch/create-batch-job.ts @@ -10,7 +10,7 @@ import { validator } from "../../../../utils/validator" * operationId: "PostBatchJobs" * summary: "Create a Batch Job" * description: "Create a Batch Job to be executed asynchronously in the Medusa backend. If `dry_run` is set to `true`, the batch job will not be executed until the it is confirmed, - * which can be done using the Confirm Batch Job endpoint." + * which can be done using the Confirm Batch Job API Route." * externalDocs: * description: "How to create a batch job" * url: "https://docs.medusajs.com/development/batch-jobs/create#create-batch-job" diff --git a/packages/medusa/src/api/routes/admin/products/create-product.ts b/packages/medusa/src/api/routes/admin/products/create-product.ts index 21e4697b1a..e0bb2216c4 100644 --- a/packages/medusa/src/api/routes/admin/products/create-product.ts +++ b/packages/medusa/src/api/routes/admin/products/create-product.ts @@ -54,7 +54,7 @@ import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/i * operationId: "PostProducts" * summary: "Create a Product" * x-authenticated: true - * description: "Create a new Product. This endpoint can also be used to create a gift card if the `is_giftcard` field is set to `true`." + * description: "Create a new Product. This API Route can also be used to create a gift card if the `is_giftcard` field is set to `true`." * requestBody: * content: * application/json: @@ -408,12 +408,12 @@ class ProductVariantReq { * type: boolean * default: true * images: - * description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL. + * description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL. * type: array * items: * type: string * thumbnail: - * description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL. + * description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL. * type: string * handle: * description: A unique handle to identify the Product by. If not provided, the kebab-case version of the product title will be used. This can be used as a slug in URLs. diff --git a/packages/medusa/src/api/routes/admin/products/update-product.ts b/packages/medusa/src/api/routes/admin/products/update-product.ts index b0a7f992ac..36df2ed6c5 100644 --- a/packages/medusa/src/api/routes/admin/products/update-product.ts +++ b/packages/medusa/src/api/routes/admin/products/update-product.ts @@ -434,12 +434,12 @@ class ProductVariantReq { * description: A flag to indicate if discounts can be applied to the Line Items generated from this Product * type: boolean * images: - * description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL. + * description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL. * type: array * items: * type: string * thumbnail: - * description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL. + * description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL. * type: string * handle: * description: A unique handle to identify the Product by. If not provided, the kebab-case version of the product title will be used. This can be used as a slug in URLs. diff --git a/packages/medusa/src/api/routes/store/customers/get-payment-methods.ts b/packages/medusa/src/api/routes/store/customers/get-payment-methods.ts index a75076cde2..89889dc7f1 100644 --- a/packages/medusa/src/api/routes/store/customers/get-payment-methods.ts +++ b/packages/medusa/src/api/routes/store/customers/get-payment-methods.ts @@ -7,7 +7,7 @@ import { PaymentProvider } from "../../../../models" * @oas [get] /store/customers/me/payment-methods * operationId: GetCustomersCustomerPaymentMethods * summary: Get Saved Payment Methods - * description: "Retrieve the logged-in customer's saved payment methods. This endpoint only works with payment providers created with the deprecated Payment Service interface. + * description: "Retrieve the logged-in customer's saved payment methods. This API Route only works with payment providers created with the deprecated Payment Service interface. * The payment methods are saved using the Payment Service's third-party service, and not on the Medusa backend. So, they're retrieved from the third-party service." * x-authenticated: true * deprecated: true diff --git a/packages/medusa/src/api/routes/store/customers/reset-password-token.ts b/packages/medusa/src/api/routes/store/customers/reset-password-token.ts index a06adc3ffb..ff4ae6d920 100644 --- a/packages/medusa/src/api/routes/store/customers/reset-password-token.ts +++ b/packages/medusa/src/api/routes/store/customers/reset-password-token.ts @@ -7,7 +7,7 @@ import { EntityManager } from "typeorm" * @oas [post] /store/customers/password-token * operationId: PostCustomersCustomerPasswordToken * summary: Request Password Reset - * description: "Create a reset password token to be used in a subsequent Reset Password endpoint. This emits the event `customer.password_reset`. If a notification provider is + * description: "Create a reset password token to be used in a subsequent Reset Password API Route. This emits the event `customer.password_reset`. If a notification provider is * installed in the Medusa backend and is configured to handle this event, a notification to the customer, such as an email, may be sent with reset instructions." * externalDocs: * description: "How to reset password" diff --git a/packages/medusa/src/api/routes/store/customers/reset-password.ts b/packages/medusa/src/api/routes/store/customers/reset-password.ts index c280b053b0..a569078331 100644 --- a/packages/medusa/src/api/routes/store/customers/reset-password.ts +++ b/packages/medusa/src/api/routes/store/customers/reset-password.ts @@ -10,7 +10,7 @@ import { MedusaError } from "medusa-core-utils" * @oas [post] /store/customers/password-reset * operationId: PostCustomersResetPassword * summary: Reset Password - * description: "Reset a Customer's password using a password token created by a previous request to the Request Password Reset endpoint. If the password token expired, + * description: "Reset a Customer's password using a password token created by a previous request to the Request Password Reset API Route. If the password token expired, * you must create a new one." * externalDocs: * description: "How to reset password" diff --git a/packages/medusa/src/api/routes/store/order-edits/complete-order-edit.ts b/packages/medusa/src/api/routes/store/order-edits/complete-order-edit.ts index 8815266b49..07153499a0 100644 --- a/packages/medusa/src/api/routes/store/order-edits/complete-order-edit.ts +++ b/packages/medusa/src/api/routes/store/order-edits/complete-order-edit.ts @@ -12,7 +12,7 @@ import { * @oas [post] /store/order-edits/{id}/complete * operationId: "PostOrderEditsOrderEditComplete" * summary: "Complete an Order Edit" - * description: "Complete an Order Edit and reflect its changes on the original order. Any additional payment required must be authorized first using the Payment Collection endpoints." + * description: "Complete an Order Edit and reflect its changes on the original order. Any additional payment required must be authorized first using the Payment Collection API Routes." * externalDocs: * description: "How to handle order edits in a storefront" * url: "https://docs.medusajs.com/modules/orders/storefront/handle-order-edits" diff --git a/packages/medusa/src/api/routes/store/orders/confirm-order-request.ts b/packages/medusa/src/api/routes/store/orders/confirm-order-request.ts index 7fd5bf3c26..22b86945c5 100644 --- a/packages/medusa/src/api/routes/store/orders/confirm-order-request.ts +++ b/packages/medusa/src/api/routes/store/orders/confirm-order-request.ts @@ -118,7 +118,7 @@ export default async (req, res) => { * - token * properties: * token: - * description: "The claim token generated by previous request to the Claim Order endpoint." + * description: "The claim token generated by previous request to the Claim Order API Route." * type: string */ export class StorePostCustomersCustomerAcceptClaimReq { diff --git a/packages/medusa/src/api/routes/store/orders/request-order.ts b/packages/medusa/src/api/routes/store/orders/request-order.ts index 35b13dfd8f..95ee900c73 100644 --- a/packages/medusa/src/api/routes/store/orders/request-order.ts +++ b/packages/medusa/src/api/routes/store/orders/request-order.ts @@ -9,7 +9,7 @@ import { TokenEvents } from "../../../../types/token" * @oas [post] /store/orders/batch/customer/token * operationId: "PostOrdersCustomerOrderClaim" * summary: "Claim Order" - * description: "Allow the logged-in customer to claim ownership of one or more orders. This generates a token that can be used later on to verify the claim using the endpoint Verify Order Claim. + * description: "Allow the logged-in customer to claim ownership of one or more orders. This generates a token that can be used later on to verify the claim using the Verify Order Claim API Route. * This also emits the event `order-update-token.created`. So, if you have a notification provider installed that handles this event and sends the customer a notification, such as an email, * the customer should receive instructions on how to finalize their claim ownership." * externalDocs: diff --git a/packages/medusa/src/api/routes/store/product-categories/list-product-categories.ts b/packages/medusa/src/api/routes/store/product-categories/list-product-categories.ts index 5d83a5886f..30540e99e2 100644 --- a/packages/medusa/src/api/routes/store/product-categories/list-product-categories.ts +++ b/packages/medusa/src/api/routes/store/product-categories/list-product-categories.ts @@ -12,7 +12,7 @@ import { defaultStoreCategoryScope } from "." * operationId: "GetProductCategories" * summary: "List Product Categories" * description: "Retrieve a list of product categories. The product categories can be filtered by fields such as `handle` or `q`. The product categories can also be paginated. - * This endpoint can also be used to retrieve a product category by its handle." + * This API Route can also be used to retrieve a product category by its handle." * x-featureFlag: "product_categories" * externalDocs: * description: "How to retrieve a product category by its handle" diff --git a/packages/medusa/src/api/routes/store/products/list-products.ts b/packages/medusa/src/api/routes/store/products/list-products.ts index 8b0ac2b514..5c40b30307 100644 --- a/packages/medusa/src/api/routes/store/products/list-products.ts +++ b/packages/medusa/src/api/routes/store/products/list-products.ts @@ -32,7 +32,7 @@ import { defaultStoreProductRemoteQueryObject } from "./index" * summary: List Products * description: | * Retrieves a list of products. The products can be filtered by fields such as `id` or `q`. The products can also be sorted or paginated. - * This endpoint can also be used to retrieve a product by its handle. + * This API Route can also be used to retrieve a product by its handle. * * For accurate and correct pricing of the products based on the customer's context, it's highly recommended to pass fields such as * `region_id`, `currency_code`, and `cart_id` when available. diff --git a/packages/medusa/src/api/routes/store/regions/list-regions.ts b/packages/medusa/src/api/routes/store/regions/list-regions.ts index db14fc74ad..0a3a120f26 100644 --- a/packages/medusa/src/api/routes/store/regions/list-regions.ts +++ b/packages/medusa/src/api/routes/store/regions/list-regions.ts @@ -11,7 +11,7 @@ import { validator } from "../../../../utils/validator" * @oas [get] /store/regions * operationId: GetRegions * summary: List Regions - * description: "Retrieve a list of regions. The regions can be filtered by fields such as `created_at`. The regions can also be paginated. This endpoint is useful to + * description: "Retrieve a list of regions. The regions can be filtered by fields such as `created_at`. The regions can also be paginated. This API Route is useful to * show the customer all available regions to choose from." * externalDocs: * description: "How to use regions in a storefront" diff --git a/packages/medusa/src/api/routes/store/returns/create-return.ts b/packages/medusa/src/api/routes/store/returns/create-return.ts index a59aedeeaf..67ce04fc18 100644 --- a/packages/medusa/src/api/routes/store/returns/create-return.ts +++ b/packages/medusa/src/api/routes/store/returns/create-return.ts @@ -280,7 +280,7 @@ class Item { * description: The quantity to return. * type: integer * reason_id: - * description: The ID of the return reason. Return reasons can be retrieved from the List Return Reasons endpoint. + * description: The ID of the return reason. Return reasons can be retrieved from the List Return Reasons API Route. * type: string * note: * description: A note to add to the item returned. diff --git a/packages/medusa/src/api/routes/store/swaps/create-swap.ts b/packages/medusa/src/api/routes/store/swaps/create-swap.ts index e3aab8edd4..97d4a8584e 100644 --- a/packages/medusa/src/api/routes/store/swaps/create-swap.ts +++ b/packages/medusa/src/api/routes/store/swaps/create-swap.ts @@ -24,7 +24,7 @@ import { validator } from "../../../../utils/validator" * summary: Create a Swap * description: | * Create a Swap for an Order. This will also create a return and associate it with the swap. If a return shipping option is specified, the return will automatically be fulfilled. - * To complete the swap, you must use the Complete Cart endpoint passing it the ID of the swap's cart. + * To complete the swap, you must use the Complete Cart API Route passing it the ID of the swap's cart. * * An idempotency key will be generated if none is provided in the header `Idempotency-Key` and added to * the response. If an error occurs during swap creation or the request is interrupted for any reason, the swap creation can be retried by passing the idempotency @@ -316,7 +316,7 @@ class AdditionalItem { * description: The quantity to return. * type: integer * reason_id: - * description: The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons endpoint. + * description: The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons API Route. * type: string * note: * description: The note to add to the item being swapped. diff --git a/www/apps/api-reference/app/_mdx/admin.mdx b/www/apps/api-reference/app/_mdx/admin.mdx index a4d905f4a2..489623461f 100644 --- a/www/apps/api-reference/app/_mdx/admin.mdx +++ b/www/apps/api-reference/app/_mdx/admin.mdx @@ -6,9 +6,9 @@ import formatReportLink from "@/utils/format-report-link" This API reference includes Medusa's Admin APIs, which are REST APIs exposed by the Medusa backend. They are typically used to perform admin functionalities or create an admin dashboard to access and manipulate your commerce store's data. -All endpoints are prefixed with `/admin`. So, during development, the endpoints will be available under the path `http://localhost:9000/admin`. For production, replace `http://localhost:9000` with your Medusa backend URL. +All API Routes are prefixed with `/admin`. So, during development, the API Routes will be available under the path `http://localhost:9000/admin`. For production, replace `http://localhost:9000` with your Medusa backend URL. -There are different ways you can send requests to these endpoints, including: +There are different ways you can send requests to these API Routes, including: - Using Medusa's [JavaScript Client](https://docs.medusajs.com/js-client/overview) - Using the [Medusa React](https://docs.medusajs.com/medusa-react/overview) library @@ -40,7 +40,7 @@ Use a user's API Token to send authenticated requests. #### How to Add API Token to a User -You can use the Update User endpoint to add or update the user's API token: +You can use the Update User API Route to add or update the user's API token: { ## Expanding Fields -In many endpoints you'll find an `expand` query parameter that can be passed -to the endpoint. You can use the `expand` query parameter to unpack an +In many API Routes you'll find an `expand` query parameter that can be passed +to the API Route. You can use the `expand` query parameter to unpack an entity's relations and return them in the response. @@ -544,8 +544,8 @@ relations like `collection`. ## Selecting Fields -In many endpoints you'll find a `fields` query parameter that can be passed -to the endpoint. You can use the `fields` query parameter to specify which +In many API Routes you'll find a `fields` query parameter that can be passed +to the API Route. You can use the `fields` query parameter to specify which fields in the entity should be returned in the response. @@ -876,7 +876,7 @@ export default Products`, This section covers how to pass some common data types as query parameters. -This is useful if you're sending requests to the API endpoints and not using +This is useful if you're sending requests to the API routes and not using the JS Client. For example, when using cURL or Postman. @@ -1028,7 +1028,7 @@ curl -g "http://localhost:9000/admin/products?created_at[lt]=2023-02-17&created_ ### Query Parameters -In listing endpoints, such as list customers or list products, you can control the pagination using the query parameters `limit` and `offset`. +In listing API Routes, such as list customers or list products, you can control the pagination using the query parameters `limit` and `offset`. `limit` is used to specify the maximum number of items that can be return in the response. `offset` is used to specify how many items to skip before returning the resulting entities. @@ -1037,7 +1037,7 @@ In listing endpoints, such as list customers or list products, you can control t You can use the `offset` query parameter to change between pages. For example, if the limit is 50, at page 1 the offset should be 0; at page 2 the offset should be 50, and so on. -For example, to limit the number of products returned in the List Products endpoint: +For example, to limit the number of products returned in the List Products API Route: { ## Expanding Fields -In many endpoints you'll find an `expand` query parameter that can be passed -to the endpoint. You can use the `expand` query parameter to unpack an +In many API Routes you'll find an `expand` query parameter that can be passed +to the API Route. You can use the `expand` query parameter to unpack an entity's relations and return them in the response. @@ -501,8 +501,8 @@ relations like `collection`. ## Selecting Fields -In many endpoints you'll find a `fields` query parameter that can be passed -to the endpoint. You can use the `fields` query parameter to specify which +In many API Routes you'll find a `fields` query parameter that can be passed +to the API Route. You can use the `fields` query parameter to specify which fields in the entity should be returned in the response. @@ -823,7 +823,7 @@ export default Products`, This section covers how to pass some common data types as query parameters. -This is useful if you're sending requests to the API endpoints and not using +This is useful if you're sending requests to the API Routes and not using our JS Client. For example, when using cURL or Postman. @@ -966,7 +966,7 @@ curl -g "http://localhost:9000/store/products?created_at[lt]=2023-02-17&created_ ### Query Parameters -In listing endpoints, such as list customers or list products, you can +In listing API Routes, such as list customers or list products, you can control the pagination using the query parameters `limit` and `offset`. @@ -981,7 +981,7 @@ offset should be `50`, and so on. For example, to limit the number of products returned in the List Products -endpoint: +API Route: {operation.externalDocs && ( <> diff --git a/www/apps/api-reference/components/Tags/Paths/index.tsx b/www/apps/api-reference/components/Tags/Paths/index.tsx index 303c5bc110..6c63423d49 100644 --- a/www/apps/api-reference/components/Tags/Paths/index.tsx +++ b/www/apps/api-reference/components/Tags/Paths/index.tsx @@ -33,7 +33,7 @@ const TagPaths = ({ tag, className }: TagPathsProps) => { const { loading } = useLoading() // if paths are already loaded since through // the expanded field, they're loaded directly - // otherwise, they're loaded using the API endpoint + // otherwise, they're loaded using the API route let paths: PathsObject = baseSpecs?.expandedTags && Object.hasOwn(baseSpecs.expandedTags, tagSlugName) diff --git a/www/apps/api-reference/specs/admin/openapi.yaml b/www/apps/api-reference/specs/admin/openapi.yaml index e4c4f082f7..e20c39aed3 100644 --- a/www/apps/api-reference/specs/admin/openapi.yaml +++ b/www/apps/api-reference/specs/admin/openapi.yaml @@ -13,11 +13,11 @@ tags: that, they can create an Oauth provider within the plugin that handles the authentication. - The Apps Oauth endpoints allows admins to manage and generate token for an + The Apps Oauth API Routes allows admins to manage and generate token for an app using its oauth provider. - name: Auth description: > - Authentication endpoints allow admin users to manage their session, such + Authentication API Routes allow admin users to manage their session, such as login or log out. When an admin user is logged in, the cookie header is set indicating the @@ -31,7 +31,7 @@ tags: asynchronusly. For example, the Import Product feature is implemented using batch jobs. - Batch Job endpoints allows admins to manage the batch jobs and their + Batch Job API Routes allows admins to manage the batch jobs and their state. externalDocs: description: How to import products @@ -41,7 +41,7 @@ tags: A store can use unlimited currencies, and each region must be associated with at least one currency. - Currencies are defined within the Medusa backend. Currency endpoints allow + Currencies are defined within the Medusa backend. Currency API Routes allow admins to list and update currencies. externalDocs: description: How to manage currencies @@ -69,7 +69,7 @@ tags: Admins can create discounts with conditions and rules, providing them with advanced settings for variety of cases. - The Discount endpoints can be used to manage discounts, their conditions, + The Discount API Routes can be used to manage discounts, their conditions, resources, and more. externalDocs: description: How to manage discounts @@ -87,7 +87,7 @@ tags: specifying options like their balance, region, and more. These gift cards are different than the saleable gift cards in a store, - which are created and managed through Product endpoints. + which are created and managed through Product API Routes. externalDocs: description: How to manage gift cards url: >- @@ -195,7 +195,7 @@ tags: Product variants are the actual salable item in your store. Each variant is a combination of the different option values available on the product. - Product variants can be managed through the Products endpoints. + Product variants can be managed through the Products API Routes. externalDocs: description: How to manage product variants url: >- @@ -207,7 +207,7 @@ tags: For example, a publishable API key can be associated with one or more sales channels. When it is passed in the header of a request to the List - Product store endpoint, + Product store API Route, the sales channels are inferred from the key and only products associated with those sales channels are retrieved. @@ -330,7 +330,7 @@ tags: url: https://docs.medusajs.com/modules/taxes/admin/manage-tax-rates - name: Uploads description: > - The upload endpoints are used to upload any type of resources. For + The upload API Routes are used to upload any type of resources. For example, they can be used to upload CSV files that are used to import products into the store. externalDocs: diff --git a/www/apps/api-reference/specs/store/openapi.yaml b/www/apps/api-reference/specs/store/openapi.yaml index 234c278574..2ec77274e7 100644 --- a/www/apps/api-reference/specs/store/openapi.yaml +++ b/www/apps/api-reference/specs/store/openapi.yaml @@ -8,7 +8,7 @@ info: tags: - name: Auth description: > - Authentication endpoints allow customers to manage their session, such as + Authentication API Routes allow customers to manage their session, such as login or log out. When a customer is logged in, the cookie header is set indicating the @@ -40,8 +40,8 @@ tags: Customers can use gift cards during checkout to deduct the gift card's balance from the checkout total. - The Gift Card endpoints allow retrieving a gift card's details by its - code. A gift card can be applied to a cart using the Carts endpoints. + The Gift Card API Routes allow retrieving a gift card's details by its + code. A gift card can be applied to a cart using the Carts API Routes. externalDocs: description: How to use gift cards in a storefront url: https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards @@ -49,8 +49,8 @@ tags: description: > Orders are purchases made by customers, typically through a storefront. - Orders are placed and created using the Carts endpoints. The Orders - endpoints allow retrieving and claiming orders. + Orders are placed and created using the Carts API Routes. The Orders + API Routes allow retrieving and claiming orders. externalDocs: description: How to retrieve order details in a storefront url: >- @@ -75,7 +75,7 @@ tags: cards](https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards) in a store. - Using these endpoints, you can filter products by categories, collections, + Using these API Routes, you can filter products by categories, collections, sales channels, and more. externalDocs: description: How to show products in a storefront @@ -89,7 +89,7 @@ tags: Products can be categoriezed into categories. A product can be associated more than one category. - Using these endpoints, you can list or retrieve a category's details and + Using these API Routes, you can list or retrieve a category's details and products. externalDocs: description: How to use product categories in a storefront @@ -100,7 +100,7 @@ tags: such as marketing or discount purposes. For example, you can create a Summer Collection. - Using these endpoints, you can list or retrieve a collection's details and + Using these API Routes, you can list or retrieve a collection's details and products. - name: Product Tags description: | diff --git a/www/apps/docs/content/admin/onboarding.md b/www/apps/docs/content/admin/onboarding.md index 767f149417..7035f16312 100644 --- a/www/apps/docs/content/admin/onboarding.md +++ b/www/apps/docs/content/admin/onboarding.md @@ -17,7 +17,7 @@ The onboarding widget is already implemented within the codebase of your Medusa By following this tutorial, you’ll: - Build an onboarding flow in the admin that takes the user through creating a sample product and order. This flow has four steps and navigates the user between four pages in the admin before completing the guide. This will be implemented using [Admin Widgets](./widgets.md). -- Keep track of the current step the user has reached by creating a table in the database and an API endpoint that the admin widget uses to retrieve and update the current step. These customizations will be applied to the backend. +- Keep track of the current step the user has reached by creating a table in the database and an API Route that the admin widget uses to retrieve and update the current step. These customizations will be applied to the backend. ![Onboarding Widget Demo](https://res.cloudinary.com/dza7lstvk/image/upload/v1686839259/Medusa%20Docs/Screenshots/onboarding-gif_nalqps.gif) @@ -45,7 +45,7 @@ If you're using TypeScript in your project, it's highly recommended to setup you ### Install Medusa React -[Medusa React](../medusa-react/overview) is a React library that facilitates using Medusa’s endpoints within your React application. It also provides the utility to register and use custom endpoints. +[Medusa React](../medusa-react/overview) is a React library that facilitates using Medusa’s API Routes within your React application. It also provides the utility to register and use custom API Routes. To install Medusa React and its required dependencies, run the following command in the root directory of the Medusa backend: @@ -78,479 +78,45 @@ export default IconProps
- -src/admin/components/shared/icons/check-circle-fill-icon.tsx + +src/admin/components/shared/icons/get-started.tsx -```tsx title=src/admin/components/shared/icons/check-circle-fill-icon.tsx +```tsx title=src/admin/components/shared/icons/get-started.tsx import React from "react" import IconProps from "../../../types/icon-type" -const CheckCircleFillIcon: React.FC = ({ - size = "24", +const GetStarted: React.FC = ({ + size = "40", color = "currentColor", ...attributes }) => { return ( - - + + + + + + + + + + ) } -export default CheckCircleFillIcon +export default GetStarted + ```
-src/admin/components/shared/icons/cross-icon.tsx - - -```tsx title=src/admin/components/shared/icons/cross-icon.tsx -import React from "react" -import IconProps from "../../../types/icon-type" - -const CrossIcon: React.FC = ({ - size = "20", - color = "currentColor", - ...attributes -}) => { - return ( - - - - - ) -} - -export default CrossIcon -``` - -
- -
- -src/admin/components/shared/icons/get-started-icon.tsx - - - - -```tsx title=src/admin/components/shared/icons/get-started-icon.tsx -import React from "react" -import IconProps from "../../../types/icon-type" - -const GetStartedIcon: React.FC = () => ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -) - -export default GetStartedIcon -``` - -
- -
- -src/admin/components/shared/icons/clipboard-copy-icon.tsx - - - - -```tsx title=src/admin/components/shared/icons/clipboard-copy-icon.tsx -import React from "react" -import IconProps from "../../../types/icon-type" - -const ClipboardCopyIcon: React.FC = ({ - size = "20", - color = "currentColor", - ...attributes -}) => { - return ( - - - - - - - ) -} - -export default ClipboardCopyIcon -``` - -
- -
- -src/admin/components/shared/icons/computer-desktop-icon.tsx - - - - -```tsx title=src/admin/components/shared/icons/computer-desktop-icon.tsx -import React from "react" -import IconProps from "../../../types/icon-type" - -const ComputerDesktopIcon: React.FC = ({ - size = "24", - color = "currentColor", - ...attributes -}) => { - return ( - - - - ) -} - -export default ComputerDesktopIcon -``` - -
- -
- -src/admin/components/shared/icons/dollar-sign-icon.tsx +src/admin/components/shared/icons/active-circle-dotted-line.tsx @@ -559,39 +125,40 @@ src/admin/components/shared/icons/dollar-sign-icon.tsx import React from "react" import IconProps from "../../../types/icon-type" -const DollarSignIcon: React.FC = ({ +const ActiveCircleDottedLine: React.FC = ({ size = "24", color = "currentColor", ...attributes }) => { return ( - - - + + + + + + + + + + + + + + + + + + + + + + + ) } -export default DollarSignIcon +export default ActiveCircleDottedLine ```
@@ -605,9 +172,10 @@ src/admin/components/shared/accordion.tsx ```tsx title=src/admin/components/shared/accordion.tsx import * as AccordionPrimitive from "@radix-ui/react-accordion" -import clsx from "clsx" import React from "react" -import CheckCircleFillIcon from "./icons/check-circle-fill-icon" +import { CheckCircleSolid, CircleMiniSolid } from "@medusajs/icons" +import { Heading, Text, clx } from "@medusajs/ui" +import ActiveCircleDottedLine from "./icons/active-circle-dotted-line" type AccordionItemProps = AccordionPrimitive.AccordionItemProps & { title: string; @@ -632,9 +200,7 @@ const Accordion: React.FC< Item: React.FC; } = ({ children, ...props }) => { return ( - - {children} - + {children} ) } @@ -654,71 +220,59 @@ const Item: React.FC = ({ triggerable, ...props }) => { - const headerClass = clsx({ - "inter-small-semibold": headingSize === "small", - "inter-base-medium": headingSize === "medium", - "inter-large-semibold": headingSize === "large", - }) - - const paddingClasses = clsx({ - "pb-0 mb-3 pt-3 ": headingSize === "medium", - "pb-5 radix-state-open:pb-5xlarge mb-5 ": - headingSize === "large", - }) - return (
-
-
+
+
{complete ? ( - + ) : ( - + {active && ( + )} - /> + {!active && ( + + )} + )}
- + {title} - {required && *} - +
{customTrigger || }
{subtitle && ( - + {subtitle} - + )}
- {description &&

{description}

} + {description && {description}}
{children}
@@ -746,376 +300,39 @@ export default Accordion
-src/admin/components/shared/spinner.tsx +src/admin/components/shared/card.tsx -```tsx title=src/admin/components/shared/spinner.tsx -import clsx from "clsx" -import React from "react" +```tsx title=src/admin/components/shared/card.tsx +import { Text, clx } from "@medusajs/ui" -type SpinnerProps = { - size?: "large" | "medium" | "small"; - variant?: "primary" | "secondary"; -}; - -const Spinner: React.FC = ({ - size = "large", - variant = "primary", -}) => { - return ( -
-
-
-
-
- ) +type CardProps = { + icon?: React.ReactNode + children?: React.ReactNode + className?: string } -export default Spinner -``` - -
- -
- -src/admin/components/shared/button.tsx - - - - - -```tsx title=src/admin/components/shared/button.tsx -import clsx from "clsx" -import React, { Children } from "react" -import Spinner from "./spinner" - -export type ButtonProps = { - variant: "primary" | "secondary" | "ghost" | "danger" | "nuclear"; - size?: "small" | "medium" | "large"; - loading?: boolean; -} & React.ButtonHTMLAttributes; - -const Button = React.forwardRef( - ( - { - variant = "primary", - size = "large", - loading = false, - children, - ...attributes - }, - ref - ) => { - const handleClick = (e) => { - if (!loading && attributes.onClick) { - attributes.onClick(e) - } - } - - const variantClassname = clsx({ - ["btn-primary"]: variant === "primary", - ["btn-secondary"]: variant === "secondary", - ["btn-ghost"]: variant === "ghost", - ["btn-danger"]: variant === "danger", - ["btn-nuclear"]: variant === "nuclear", - }) - - const sizeClassname = clsx({ - ["btn-large"]: size === "large", - ["btn-medium"]: size === "medium", - ["btn-small"]: size === "small", - }) - - return ( - - ) - } -) - -export default Button -``` - -
- -
- -src/admin/components/shared/code-snippets.tsx - - - - -```tsx title=src/admin/components/shared/code-snippets.tsx -import React, { useState } from "react" -import clsx from "clsx" -import copy from "copy-to-clipboard" -import { Highlight, themes } from "prism-react-renderer" -import ClipboardCopyIcon from "./icons/clipboard-copy-icon" -import CheckCircleFillIcon from "./icons/check-circle-fill-icon" - -const CodeSnippets = ({ - snippets, -}: { - snippets: { - label: string; - language: string; - code: string; - }[]; -}) => { - const [active, setActive] = useState(snippets[0]) - const [copied, setCopied] = useState(false) - - const copyToClipboard = () => { - setCopied(true) - copy(active.code) - setTimeout(() => { - setCopied(false) - }, 3000) - } - - return ( -
-
- {snippets.map((snippet) => ( -
setActive(snippet)} - > - {snippet.label} -
- ))} -
-
-
- {copied ? ( - - ) : ( - - )} -
- - {({ style, tokens, getLineProps, getTokenProps }) => ( -
-              {tokens.map((line, i) => (
-                
- {line.map((token, key) => ( - - ))} -
- ))} -
- )} -
-
-
- ) -} - -export default CodeSnippets -``` - -
- -
- -src/admin/components/shared/container.tsx - - - - -```tsx title=src/admin/components/shared/container.tsx -import React, { PropsWithChildren } from "react" - -type Props = PropsWithChildren<{ - title?: string; - description?: string; -}>; - -export const Container = ({ title, description, children }: Props) => { - return ( -
-
-
- {title && ( -

{title}

- )} -
- {description && ( -

{description}

- )} -
-
{children}
-
- ) -} -``` - -
- -
- -src/admin/components/shared/badge.tsx - - - - -```tsx title=src/admin/components/shared/badge.tsx -import clsx from "clsx" -import React from "react" - -type BadgeProps = { - variant: - | "primary" - | "danger" - | "success" - | "warning" - | "ghost" - | "default" - | "disabled" - | "new-feature" -} & React.HTMLAttributes - -const Badge: React.FC = ({ +const Card = ({ + icon, children, - variant, - onClick, className, - ...props -}) => { - const variantClassname = clsx({ - ["badge-primary"]: variant === "primary", - ["badge-danger"]: variant === "danger", - ["badge-success"]: variant === "success", - ["badge-warning"]: variant === "warning", - ["badge-ghost"]: variant === "ghost", - ["badge-default"]: variant === "default", - ["badge-disabled"]: variant === "disabled", - ["bg-blue-10 border-blue-30 border font-normal text-blue-50"]: - variant === "new-feature", - }) - +}: CardProps) => { return ( -
- {children} +
+ {icon} + {children}
) } -export default Badge -``` - -
- -
- -src/admin/components/shared/icon-badge.tsx - - - - -```tsx title=src/admin/components/shared/icon-badge.tsx -import clsx from "clsx" -import React from "react" -import Badge from "./badge" - -type IconBadgeProps = { - variant?: - | "primary" - | "danger" - | "success" - | "warning" - | "ghost" - | "default" - | "disabled"; -} & React.HTMLAttributes; - -const IconBadge: React.FC = ({ - children, - variant, - className, - ...rest -}) => { - return ( - - {children} - - ) -} - -export default IconBadge +export default Card ```
@@ -1133,7 +350,7 @@ If you’re not interested in learning about backend customizations, you can ski In this step, you’ll customize the Medusa backend to: 1. Add a new table in the database that stores the current onboarding step. This requires creating a new entity, repository, and migration. -2. Add a new endpoint that allows to retrieve and update the current onboarding step. This requires creating a new service and endpoint. +2. Add new API Routes that allow retrieving and updating the current onboarding step. This also requires creating a new service. ### Create Entity @@ -1235,9 +452,9 @@ You can learn more about migrations in [this guide](../development/entities/migr ### Create Service -A [service](../development/services/overview.mdx) is a class that holds helper methods related to an entity. For example, methods to create or retrieve a record of that entity. Services are used by other resources, such as endpoints, to perform functionalities related to an entity. +A [service](../development/services/overview.mdx) is a class that holds helper methods related to an entity. For example, methods to create or retrieve a record of that entity. Services are used by other resources, such as API Routes, to perform functionalities related to an entity. -So, before you add the endpoints that allow retrieving and updating the onboarding state, you need to add the service that implements these helper functionalities. +So, before you add the API Routes that allow retrieving and updating the onboarding state, you need to add the service that implements these helper functionalities. Start by creating the file `src/types/onboarding.ts` with the following content: @@ -1327,19 +544,24 @@ This service class implements two methods `retrieve` to retrieve the current onb You can learn more about services in [this documentation](../development/services/overview.mdx). -### Create Endpoint +### Create API Routes -The last part of this step is to create the [endpoints](../development/endpoints/overview) that you’ll consume in the admin widget. There will be two endpoints: Get Onboarding State and Update Onboarding State. +The last part of this step is to create the [API Routes](../development/api-routes/overview) that you’ll consume in the admin widget. There will be two API Routes: Get Onboarding State and Update Onboarding State. -To add the Get Onboarding State endpoint, create the file `src/api/routes/admin/onboarding/get-status.ts` with the following content: +To add these API Routes, create the file `src/api/admin/onboarding/route.ts` with the following content: -```ts title=src/api/routes/admin/onboarding/get-status.ts -import { Request, Response } from "express" -import OnboardingService from "../../../../services/onboarding" +```ts title=src/api/admin/onboarding/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { EntityManager } from "typeorm" -export default async function getOnboardingStatus( - req: Request, - res: Response +import OnboardingService from "../../../services/onboarding" + +export async function GET( + req: MedusaRequest, + res: MedusaResponse ) { const onboardingService: OnboardingService = req.scope.resolve("onboardingService") @@ -1348,20 +570,10 @@ export default async function getOnboardingStatus( res.status(200).json({ status }) } -``` -Notice how this endpoint uses the `OnboardingService`'s `retrieve` method to retrieve the current onboarding state. It resolves the `OnboardingService` using the [Dependency Container.](../development/fundamentals/dependency-injection.md) - -To add the Update Onboarding State, create the file `src/api/routes/admin/onboarding/update-status.ts` with the following content: - -```ts title=src/api/routes/admin/onboarding/update-status.ts -import { Request, Response } from "express" -import { EntityManager } from "typeorm" -import OnboardingService from "../../../../services/onboarding" - -export default async function updateOnboardingStatus( - req: Request, - res: Response +export async function POST( + req: MedusaRequest, + res: MedusaResponse ) { const onboardingService: OnboardingService = req.scope.resolve("onboardingService") @@ -1372,133 +584,16 @@ export default async function updateOnboardingStatus( return await onboardingService .withTransaction(transactionManager) .update(req.body) - }) + } + ) res.status(200).json({ status }) } ``` -Notice how this endpoint uses the `OnboardingService`'s `update` method to update the current onboarding state. +Notice how these API Routes use the `OnboardingService`'s `retrieve` and `update` methods to retrieve and update the current onboarding state. They resolve the `OnboardingService` using the [Dependency Container](../development/fundamentals/dependency-injection.md). -After creating the endpoints, you need to register them in a router and export the router for the Medusa core to load. - -To do that, start by creating the file `src/api/routes/admin/onboarding/index.ts` with the following content: - -```ts title=src/api/routes/admin/onboarding/index.ts -import { wrapHandler } from "@medusajs/utils" -import { Router } from "express" -import getOnboardingStatus from "./get-status" -import updateOnboardingStatus from "./update-status" - -const router = Router() - -export default (adminRouter: Router) => { - adminRouter.use("/onboarding", router) - - router.get("/", wrapHandler(getOnboardingStatus)) - router.post("/", wrapHandler(updateOnboardingStatus)) -} -``` - -This file creates a router that registers the Get Onboarding State and Update Onboarding State endpoints. - -Next, create or change the content of the file `src/api/routes/admin/index.ts` to the following: - -```ts title=src/api/routes/admin/index.ts -import { Router } from "express" -import { wrapHandler } from "@medusajs/medusa" -import onboardingRoutes from "./onboarding" -import customRouteHandler from "./custom-route-handler" - -// Initialize a custom router -const router = Router() - -export function attachAdminRoutes(adminRouter: Router) { - // Attach our router to a custom path on the admin router - adminRouter.use("/custom", router) - - // Define a GET endpoint on the root route of our custom path - router.get("/", wrapHandler(customRouteHandler)) - - // Attach routes for onboarding experience, defined separately - onboardingRoutes(adminRouter) -} -``` - -This file exports the router created in `src/api/routes/admin/onboarding/index.ts`. - -Finally, create or change the content of the file `src/api/index.ts` to the following content: - -```ts title=src/api/index.ts -import { Router } from "express" -import cors from "cors" -import bodyParser from "body-parser" -import { authenticate, ConfigModule } from "@medusajs/medusa" -import { getConfigFile } from "medusa-core-utils" -import { attachStoreRoutes } from "./routes/store" -import { attachAdminRoutes } from "./routes/admin" - -export default (rootDirectory: string): Router | Router[] => { - // Read currently-loaded medusa config - const { configModule } = getConfigFile( - rootDirectory, - "medusa-config" - ) - const { projectConfig } = configModule - - // Set up our CORS options objects, based on config - const storeCorsOptions = { - origin: projectConfig.store_cors.split(","), - credentials: true, - } - - const adminCorsOptions = { - origin: projectConfig.admin_cors.split(","), - credentials: true, - } - - // Set up express router - const router = Router() - - // Set up root routes for store and admin endpoints, - // with appropriate CORS settings - router.use( - "/store", - cors(storeCorsOptions), - bodyParser.json() - ) - router.use( - "/admin", - cors(adminCorsOptions), - bodyParser.json() - ) - - // Add authentication to all admin routes *except* - // auth and account invite ones - router.use( - /\/admin\/((?!auth)(?!invites).*)/, - authenticate() - ) - - // Set up routers for store and admin endpoints - const storeRouter = Router() - const adminRouter = Router() - - // Attach these routers to the root routes - router.use("/store", storeRouter) - router.use("/admin", adminRouter) - - // Attach custom routes to these routers - attachStoreRoutes(storeRouter) - attachAdminRoutes(adminRouter) - - return router -} -``` - -This is the file that the Medusa core loads the endpoints from. In this file, you export a router that registers store and admin endpoints, including the `onboarding` endpoints you just added. - -You can learn more about endpoints in [this documentation](../development/endpoints/overview.mdx). +You can learn more about API Routes in [this documentation](../development/api-routes/overview.mdx). --- @@ -1512,42 +607,46 @@ Create the file `src/admin/widgets/onboarding-flow/onboarding-flow.tsx` with the ```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -import React, { - useState, - useEffect, -} from "react" -import { - Container, -} from "../../components/shared/container" -import Button from "../../components/shared/button" -import { - WidgetConfig, -} from "@medusajs/admin" -import Accordion from "../../components/shared/accordion" -import GetStartedIcon from "../../components/shared/icons/get-started-icon" -import { - OnboardingState, -} from "../../../models/onboarding" -import { - useNavigate, -} from "react-router-dom" +import { OrderDetailsWidgetProps, ProductDetailsWidgetProps, WidgetConfig, WidgetProps } from "@medusajs/admin" +import { useAdminCustomPost, useAdminCustomQuery, useMedusa } from "medusa-react" +import React, { useEffect, useState, useMemo, useCallback } from "react" +import { useNavigate, useSearchParams, useLocation } from "react-router-dom" +import { OnboardingState } from "../../../models/onboarding" import { AdminOnboardingUpdateStateReq, OnboardingStateRes, UpdateOnboardingStateInput, } from "../../../types/onboarding" +import OrderDetailDefault from "../../components/onboarding-flow/default/orders/order-detail" +import OrdersListDefault from "../../components/onboarding-flow/default/orders/orders-list" +import ProductDetailDefault from "../../components/onboarding-flow/default/products/product-detail" +import ProductsListDefault from "../../components/onboarding-flow/default/products/products-list" +import { Button, Container, Heading, Text, clx } from "@medusajs/ui" +import Accordion from "../../components/shared/accordion" +import GetStarted from "../../components/shared/icons/get-started" +import { Order, Product } from "@medusajs/medusa" +import ProductsListNextjs from "../../components/onboarding-flow/nextjs/products/products-list" +import ProductDetailNextjs from "../../components/onboarding-flow/nextjs/products/product-detail" +import OrdersListNextjs from "../../components/onboarding-flow/nextjs/orders/orders-list" +import OrderDetailNextjs from "../../components/onboarding-flow/nextjs/orders/order-detail" type STEP_ID = | "create_product" | "preview_product" | "create_order" - | "setup_finished"; + | "setup_finished" + | "create_product_nextjs" + | "preview_product_nextjs" + | "create_order_nextjs" + | "setup_finished_nextjs" -export type StepContentProps = any & { +type OnboardingWidgetProps = WidgetProps | ProductDetailsWidgetProps | OrderDetailsWidgetProps + +export type StepContentProps = OnboardingWidgetProps & { onNext?: Function; isComplete?: boolean; data?: OnboardingState; -} & any; +}; type Step = { id: STEP_ID; @@ -1556,36 +655,36 @@ type Step = { onNext?: Function; }; -const STEP_FLOW: STEP_ID[] = [ - "create_product", - "preview_product", - "create_order", - "setup_finished", -] +const QUERY_KEY = ["onboarding_state"] + +const OnboardingFlow = (props: OnboardingWidgetProps) => { + // create custom hooks for custom API Routes + const { data, isLoading } = useAdminCustomQuery< + undefined, + OnboardingStateRes + >("/onboarding", QUERY_KEY) + const { mutate } = useAdminCustomPost< + AdminOnboardingUpdateStateReq, + OnboardingStateRes + >("/onboarding", QUERY_KEY) -const OnboardingFlow = (props: any) => { const navigate = useNavigate() + const location = useLocation() + // will be used if onboarding step + // is passed as a path parameter + const { client } = useMedusa() - // TODO change based on state in backend - const currentStep: STEP_ID | undefined = "create_product" as STEP_ID + // get current step from custom API Route + const currentStep: STEP_ID | undefined = useMemo(() => { + return data?.status + ?.current_step as STEP_ID + }, [data]) + // initialize some state const [openStep, setOpenStep] = useState(currentStep) const [completed, setCompleted] = useState(false) - useEffect(() => { - setOpenStep(currentStep) - if (currentStep === STEP_FLOW[STEP_FLOW.length - 1]) {setCompleted(true)} - }, [currentStep]) - - const updateServerState = (payload: any) => { - // TODO update state in the backend - } - - const onStart = () => { - // TODO update state in the backend - navigate(`/a/products`) - } - + // this method is used to move from one step to the next const setStepComplete = ({ step_id, extraData, @@ -1595,176 +694,409 @@ const OnboardingFlow = (props: any) => { extraData?: UpdateOnboardingStateInput; onComplete?: () => void; }) => { - // TODO update state in the backend - } - - const goToProductView = (product: any) => { - setStepComplete({ - step_id: "create_product", - extraData: { product_id: product.id }, - onComplete: () => navigate(`/a/products/${product.id}`), + const next = steps[findStepIndex(step_id) + 1] + mutate({ current_step: next.id, ...extraData }, { + onSuccess: onComplete, }) } - const goToOrders = () => { - setStepComplete({ - step_id: "preview_product", - onComplete: () => navigate(`/a/orders`), - }) - } - - const goToOrderView = (order: any) => { - setStepComplete({ - step_id: "create_order", - onComplete: () => navigate(`/a/orders/${order.id}`), - }) + // this is useful if you want to change the current step + // using a path parameter. It can only be changed if the passed + // step in the path parameter is the next step. + const [ searchParams ] = useSearchParams() + + // the steps are set based on the + // onboarding type + const steps: Step[] = useMemo(() => { + { + switch(process.env.MEDUSA_ADMIN_ONBOARDING_TYPE) { + case "nextjs": + return [ + { + id: "create_product_nextjs", + title: "Create Products", + component: ProductsListNextjs, + onNext: (product: Product) => { + setStepComplete({ + step_id: "create_product_nextjs", + extraData: { product_id: product.id }, + onComplete: () => { + if (!location.pathname.startsWith(`/a/products/${product.id}`)) { + navigate(`/a/products/${product.id}`) + } + }, + }) + }, + }, + { + id: "preview_product_nextjs", + title: "Preview Product in your Next.js Storefront", + component: ProductDetailNextjs, + onNext: () => { + setStepComplete({ + step_id: "preview_product_nextjs", + onComplete: () => navigate(`/a/orders`), + }) + }, + }, + { + id: "create_order_nextjs", + title: "Create an Order using your Next.js Storefront", + component: OrdersListNextjs, + onNext: (order: Order) => { + setStepComplete({ + step_id: "create_order_nextjs", + onComplete: () => { + if (!location.pathname.startsWith(`/a/orders/${order.id}`)) { + navigate(`/a/orders/${order.id}`) + } + }, + }) + }, + }, + { + id: "setup_finished_nextjs", + title: "Setup Finished: Continue Building your Ecommerce Store", + component: OrderDetailNextjs, + }, + ] + default: + return [ + { + id: "create_product", + title: "Create Product", + component: ProductsListDefault, + onNext: (product: Product) => { + setStepComplete({ + step_id: "create_product", + extraData: { product_id: product.id }, + onComplete: () => { + if (!location.pathname.startsWith(`/a/products/${product.id}`)) { + navigate(`/a/products/${product.id}`) + } + }, + }) + }, + }, + { + id: "preview_product", + title: "Preview Product", + component: ProductDetailDefault, + onNext: () => { + setStepComplete({ + step_id: "preview_product", + onComplete: () => navigate(`/a/orders`), + }) + }, + }, + { + id: "create_order", + title: "Create an Order", + component: OrdersListDefault, + onNext: (order: Order) => { + setStepComplete({ + step_id: "create_order", + onComplete: () => { + if (!location.pathname.startsWith(`/a/orders/${order.id}`)) { + navigate(`/a/orders/${order.id}`) + } + }, + }) + }, + }, + { + id: "setup_finished", + title: "Setup Finished: Start developing with Medusa", + component: OrderDetailDefault, + }, + ] + } + } + }, [location.pathname]) + + // used to retrieve the index of a step by its ID + const findStepIndex = useCallback((step_id: STEP_ID) => { + return steps.findIndex((step) => step.id === step_id) + }, [steps]) + + // used to check if a step is completed + const isStepComplete = useCallback((step_id: STEP_ID) => { + return findStepIndex(currentStep) > findStepIndex(step_id) + }, [findStepIndex, currentStep]) + + // this is used to retrieve the data necessary + // to move to the next onboarding step + const getOnboardingParamStepData = useCallback(async (onboardingStep: string, data?: { + orderId?: string, + productId?: string, + }) => { + switch (onboardingStep) { + case "setup_finished_nextjs": + case "setup_finished": + if (!data?.orderId && "order" in props) { + return props.order + } + const orderId = data?.orderId || searchParams.get("order_id") + if (orderId) { + return (await client.admin.orders.retrieve(orderId)).order + } + + throw new Error ("Required `order_id` parameter was not passed as a parameter") + case "preview_product_nextjs": + case "preview_product": + if (!data?.productId && "product" in props) { + return props.product + } + const productId = data?.productId || searchParams.get("product_id") + if (productId) { + return (await client.admin.products.retrieve(productId)).product + } + + throw new Error ("Required `product_id` parameter was not passed as a parameter") + default: + return undefined + } + }, [searchParams, props]) + + const isProductCreateStep = useMemo(() => { + return currentStep === "create_product" || + currentStep === "create_product_nextjs" + }, [currentStep]) + + const isOrderCreateStep = useMemo(() => { + return currentStep === "create_order" || + currentStep === "create_order_nextjs" + }, [currentStep]) + + // used to change the open step when the current + // step is retrieved from custom API Routes + useEffect(() => { + setOpenStep(currentStep) + + if (findStepIndex(currentStep) === steps.length - 1) {setCompleted(true)} + }, [currentStep, findStepIndex]) + + // used to check if the user created a product and has entered its details page + // the step is changed to the next one + useEffect(() => { + if (location.pathname.startsWith("/a/products/prod_") && isProductCreateStep && "product" in props) { + // change to the preview product step + const currentStepIndex = findStepIndex(currentStep) + steps[currentStepIndex].onNext?.(props.product) + } + }, [location.pathname, isProductCreateStep]) + + // used to check if the user created an order and has entered its details page + // the step is changed to the next one. + useEffect(() => { + if (location.pathname.startsWith("/a/orders/order_") && isOrderCreateStep && "order" in props) { + // change to the preview product step + const currentStepIndex = findStepIndex(currentStep) + steps[currentStepIndex].onNext?.(props.order) + } + }, [location.pathname, isOrderCreateStep]) + + // used to check if the `onboarding_step` path + // parameter is passed and, if so, moves to that step + // only if it's the next step and its necessary data is passed + useEffect(() => { + const onboardingStep = searchParams.get("onboarding_step") as STEP_ID + const onboardingStepIndex = findStepIndex(onboardingStep) + if (onboardingStep && onboardingStepIndex !== -1 && onboardingStep !== openStep) { + // change current step to the onboarding step + const openStepIndex = findStepIndex(openStep) + + if (onboardingStepIndex !== openStepIndex + 1) { + // can only go forward one step + return + } + + // retrieve necessary data and trigger the next function + getOnboardingParamStepData(onboardingStep) + .then((data) => { + steps[openStepIndex].onNext?.(data) + }) + .catch((e) => console.error(e)) + } + }, [searchParams, openStep, getOnboardingParamStepData]) + + if ( + !isLoading && + data?.status?.is_complete && + !localStorage.getItem("override_onboarding_finish") + ) + {return null} + + // a method that will be triggered when + // the setup is started + const onStart = () => { + mutate({ current_step: steps[0].id }) + navigate(`/a/products`) } + // a method that will be triggered when + // the setup is completed const onComplete = () => { setCompleted(true) } + // a method that will be triggered when + // the setup is closed const onHide = () => { - updateServerState({ is_complete: true }) + mutate({ is_complete: true }) } - // TODO add steps - const Steps: Step[] = [] + // used to get text for get started header + const getStartedText = () => { + switch(process.env.MEDUSA_ADMIN_ONBOARDING_TYPE) { + case "nextjs": + return "Learn the basics of Medusa by creating your first order using the Next.js storefront." + default: + return "Learn the basics of Medusa by creating your first order." + } + } - const isStepComplete = (step_id: STEP_ID) => - STEP_FLOW.indexOf(currentStep) > STEP_FLOW.indexOf(step_id) - - return ( - <> - - setOpenStep(value as STEP_ID)} - > -
-
- -
- {!completed ? ( - <> -
-

Get started

-

- Learn the basics of Medusa by creating your first order. -

-
-
- {currentStep ? ( - <> - {currentStep === STEP_FLOW[STEP_FLOW.length - 1] ? ( - - ) : ( - - )} - - ) : ( - <> - + return ( + <> + + setOpenStep(value as STEP_ID)} + > +
+
+ +
+ {!completed ? ( + <> +
+ Get started + + {getStartedText()} + +
+
+ {!!currentStep ? ( + <> + {currentStep === steps[steps.length - 1].id ? ( - - )} -
- - ) : ( - <> -
-

- Thank you for completing the setup guide! -

-

- This whole experience was built using our new{" "} - widgets feature. -
You can find out more details and build your own by - following{" "} - onHide()} + > + Cancel Setup + + )} + + ) : ( + <> +

-
- + + + )} +
+ + ) : ( + <> +
+ + Thank you for completing the setup guide! + + + This whole experience was built using our new{" "} + widgets feature. +
You can find out more details and build your own by + following{" "} + - Close - -
- - )} + our guide + + . + +
+
+ +
+ + )} +
+ { +
+ {(!completed ? steps : steps.slice(-1)).map((step) => { + const isComplete = isStepComplete(step.id) + const isCurrent = currentStep === step.id + return ( + , + })} + > +
+ +
+
+ ) + })}
- { -
- {(!completed ? Steps : Steps.slice(-1)).map((step, index) => { - const isComplete = isStepComplete(step.id) - const isCurrent = currentStep === step.id - return ( - , - })} - > -
- -
-
- ) - })} -
- } - - - - ) + } + + + + ) } export const config: WidgetConfig = { @@ -1779,6 +1111,8 @@ export const config: WidgetConfig = { export default OnboardingFlow ``` +Notice that you'll see errors related to components not being defined. You'll create these components in upcoming sections. + There are three important details to ensure that Medusa reads this file as a widget: 1. The file is placed under the `src/admin/widget` directory. @@ -1787,7 +1121,9 @@ There are three important details to ensure that Medusa reads this file as a wid The extension uses `react-router-dom`, which is available as a dependency of the `@medusajs/admin` package, to navigate to other pages in the dashboard. -The `OnboardingFlow` widget also implements functionalities related to handling the steps of the onboarding flow, including navigating between them and updating the current step in the backend. Some parts are left as `TODO` until you add the components for each step, and you implement customizations in the backend. +The `OnboardingFlow` widget also implements functionalities related to handling the steps of the onboarding flow, including navigating between them and updating the current step in the backend. + +To use the custom API Routes created in a previous step, you use the `useAdminCustomQuery` and `useAdminCustomPost` hooks from the `medusa-react` package. You can learn more about these hooks in the [Medusa React](../medusa-react/overview.mdx#custom-hooks) documentation. You can learn more about Admin Widgets in [this documentation](./widgets.md). @@ -1797,44 +1133,43 @@ You can learn more about Admin Widgets in [this documentation](./widgets.md). In this section, you’ll create the components for each step in the onboarding flow. You’ll then update the `OnboardingFlow` widget to use these components. +Notice that as there are two types of flows, you'll be creating the components for the default flow and for the Next.js flow. +
-ProductsList component +ProductsListDefault component -The `ProductsList` component is used in the first step of the onboarding widget. It allows the user to either open the Create Product modal or create a sample product. +The `ProductsListDefault` component is used in the first step of the onboarding widget's default flow. It allows the user to create a sample product. -Create the file `src/admin/components/onboarding-flow/products/products-list.tsx` with the following content: +Create the file `src/admin/components/onboarding-flow/default/products/products-list.tsx` with the following content: -```tsx title=src/admin/components/onboarding-flow/products/products-list.tsx -import React from "react" -import Button from "../../shared/button" +```tsx title=src/admin/components/onboarding-flow/default/products/products-list.tsx +import React, { useMemo } from "react" import { useAdminCreateProduct, useAdminCreateCollection, + useMedusa, } from "medusa-react" -import { - useAdminRegions, -} from "medusa-react" -import { - StepContentProps, -} from "../../../widgets/onboarding-flow/onboarding-flow" +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, Text } from "@medusajs/ui" +import getSampleProducts from "../../../../utils/sample-products" +import prepareRegions from "../../../../utils/prepare-region" -enum ProductStatus { - PUBLISHED = "published", -} - -const ProductsList = ({ onNext, isComplete }: StepContentProps) => { +const ProductsListDefault = ({ onNext, isComplete }: StepContentProps) => { const { mutateAsync: createCollection, isLoading: collectionLoading } = useAdminCreateCollection() const { mutateAsync: createProduct, isLoading: productLoading } = useAdminCreateProduct() - const { regions } = useAdminRegions() + const { client } = useMedusa() - const isLoading = collectionLoading || productLoading + const isLoading = useMemo(() => + collectionLoading || productLoading, + [collectionLoading, productLoading] + ) const createSample = async () => { try { @@ -1842,62 +1177,14 @@ const ProductsList = ({ onNext, isComplete }: StepContentProps) => { title: "Merch", handle: "merch", }) - const { product } = await createProduct({ - title: "Medusa T-Shirt", - description: "Comfy t-shirt with Medusa logo", - subtitle: "Black", - is_giftcard: false, - discountable: false, - options: [{ title: "Size" }], - images: [ - "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-black-front.png", - "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-black-back.png", - ], + + const regions = await prepareRegions(client) + + const sampleProducts = getSampleProducts({ + regions, collection_id: collection.id, - variants: [ - { - title: "Small", - inventory_quantity: 25, - manage_inventory: true, - prices: regions.map((region) => ({ - amount: 5000, - currency_code: region.currency_code, - })), - options: [{ value: "S" }], - }, - { - title: "Medium", - inventory_quantity: 10, - manage_inventory: true, - prices: regions.map((region) => ({ - amount: 5000, - currency_code: region.currency_code, - })), - options: [{ value: "M" }], - }, - { - title: "Large", - inventory_quantity: 17, - manage_inventory: true, - prices: regions.map((region) => ({ - amount: 5000, - currency_code: region.currency_code, - })), - options: [{ value: "L" }], - }, - { - title: "Extra Large", - inventory_quantity: 22, - manage_inventory: true, - prices: regions.map((region) => ({ - amount: 5000, - currency_code: region.currency_code, - })), - options: [{ value: "XL" }], - }, - ], - status: ProductStatus.PUBLISHED, }) + const { product } = await createProduct(sampleProducts[0]) onNext(product) } catch (e) { console.error(e) @@ -1906,22 +1193,23 @@ const ProductsList = ({ onNext, isComplete }: StepContentProps) => { return (
-

+ Create a product and set its general details such as title and - description, its price, options, variants, images, and more. You'll then + description, its price, options, variants, images, and more. You'll then use the product to create a sample order. -

-

- If you're not ready to create a product, we can create a sample product - for you. -

+ + + You can create a product by clicking the "New Product" button below. + Alternatively, if you're not ready to create your own product, we can + create a sample one for you. + {!isComplete && ( -
+
@@ -1931,84 +1219,105 @@ const ProductsList = ({ onNext, isComplete }: StepContentProps) => { ) } -export default ProductsList +export default ProductsListDefault ```
-ProductDetail component +ProductDetailDefault component -The `ProductDetail` component is used in the second step of the onboarding. It shows the user a code snippet to preview the product they created in the first step. +The `ProductDetailDefault` component is used in the second step of the onboarding's default flow. It shows the user a code snippet to preview the product created in the first step. -Create the file `src/admin/components/onboarding-flow/products/product-detail.tsx` with the following content: +Create the file `src/admin/components/onboarding-flow/default/products/product-detail.tsx` with the following content: -```tsx title=src/admin/components/onboarding-flow/products/product-detail.tsx -import React from "react" +```tsx title=src/admin/components/onboarding-flow/default/products/product-detail.tsx +import React, { useEffect, useMemo } from "react" import { useAdminPublishableApiKeys, + useAdminCreatePublishableApiKey, } from "medusa-react" -import Button from "../../shared/button" -import CodeSnippets from "../../shared/code-snippets" -import { - StepContentProps, -} from "../../../widgets/onboarding-flow/onboarding-flow" +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, CodeBlock, Text } from "@medusajs/ui" -const ProductDetail = ({ onNext, isComplete, data }: StepContentProps) => { - const { - publishable_api_keys: keys, - isLoading, - } = useAdminPublishableApiKeys({ +const ProductDetailDefault = ({ onNext, isComplete, data }: StepContentProps) => { + const { publishable_api_keys: keys, isLoading, refetch } = useAdminPublishableApiKeys({ offset: 0, limit: 1, }) - const api_key = keys?.[0]?.id || "pk_01H0PY648BTMEJR34ZDATXZTD9" + const createPublishableApiKey = useAdminCreatePublishableApiKey() + + const api_key = useMemo(() => keys?.[0]?.id || "", [keys]) + const backendUrl = process.env.MEDUSA_BACKEND_URL === "/" || process.env.MEDUSA_ADMIN_BACKEND_URL === "/" ? + location.origin : + process.env.MEDUSA_BACKEND_URL || process.env.MEDUSA_ADMIN_BACKEND_URL || "http://location:9000" + + useEffect(() => { + if (!isLoading && !keys?.length) { + createPublishableApiKey.mutate({ + "title": "Development", + }, { + onSuccess: () => { + refetch() + }, + }) + } + }, [isLoading, keys]) + return (
-

On this page, you can view your product's details and edit them.

-

- You can preview your product using Medusa's Store APIs. You can copy any - of the following code snippets to try it out. -

-
+
+ On this page, you can view your product's details and edit them. + + You can preview your product using Medusa's Store APIs. You can copy any + of the following code snippets to try it out. + +
+
{!isLoading && ( - + {\n // ...\n const productService = await initializeProductModule()\n const products = await productService.list({\n id: "${data?.product_id}",\n })\n\n console.log(products[0])\n}`, + }, + ]} className="my-6"> + + + )}
-
+
- {!isComplete && ( - )} @@ -2017,64 +1326,56 @@ const ProductDetail = ({ onNext, isComplete, data }: StepContentProps) => { ) } -export default ProductDetail +export default ProductDetailDefault ```
-OrdersList component +OrdersListDefault component -The `OrdersList` component is used in the third step of the onboarding. It allows the user to create a sample order. +The `OrdersListDefault` component is used in the third step of the onboarding's default flow. It allows the user to create a sample order. -Create the file `src/admin/components/onboarding-flow/orders/orders-list.tsx` with the following content: +Create the file `src/admin/components/onboarding-flow/default/orders/orders-list.tsx` with the following content: -```tsx title=src/admin/components/onboarding-flow/orders/orders-list.tsx +```tsx title=src/admin/components/onboarding-flow/default/orders/orders-list.tsx import React from "react" -import Button from "../../shared/button" import { useAdminProduct, -} from "medusa-react" -import { useAdminCreateDraftOrder, -} from "medusa-react" -import { - useAdminShippingOptions, -} from "medusa-react" -import { - useAdminRegions, -} from "medusa-react" -import { useMedusa, } from "medusa-react" -import { - StepContentProps, -} from "../../../widgets/onboarding-flow/onboarding-flow" +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, Text } from "@medusajs/ui" +import prepareRegions from "../../../../utils/prepare-region" +import prepareShippingOptions from "../../../../utils/prepare-shipping-options" -const OrdersList = ({ onNext, isComplete, data }: StepContentProps) => { +const OrdersListDefault = ({ onNext, isComplete, data }: StepContentProps) => { const { product } = useAdminProduct(data.product_id) const { mutateAsync: createDraftOrder, isLoading } = useAdminCreateDraftOrder() const { client } = useMedusa() - const { regions } = useAdminRegions() - const { shipping_options } = useAdminShippingOptions() - const createOrder = async () => { const variant = product.variants[0] ?? null try { + // check if there is a shipping option and a region + // and if not, create demo ones + const regions = await prepareRegions(client) + const shipping_options = await prepareShippingOptions(client, regions[0]) + const { draft_order } = await createDraftOrder({ email: "customer@medusajs.com", items: [ variant ? { quantity: 1, - variant_id: variant.id, + variant_id: variant?.id, } : { quantity: 1, @@ -2099,19 +1400,21 @@ const OrdersList = ({ onNext, isComplete, data }: StepContentProps) => { } return ( <> -
-

- With a Product created, we can now place an Order. Click the button - below to create a sample order. -

+
+ + The last step is to create a sample order using the product you just created. You can then view your order’s details, process its payment, fulfillment, inventory, and more. + + + By clicking the “Create a Sample Order” button, we’ll generate an order using the product you created and default configurations. +
{!isComplete && ( @@ -2121,96 +1424,132 @@ const OrdersList = ({ onNext, isComplete, data }: StepContentProps) => { ) } -export default OrdersList +export default OrdersListDefault ```
-OrderDetail component +OrderDetailDefault component -The `OrderDetail` component is used in the fourth and final step of the onboarding. It educates the user on the next steps when developing with Medusa. +The `OrderDetailDefault` component is used in the fourth and final step of the onboarding's default flow. It educates the user on the next steps when developing with Medusa. -Create the file `src/admin/components/onboarding-flow/orders/order-detail.tsx` with the following content: +Create the file `src/admin/components/onboarding-flow/default/orders/order-detail.tsx` with the following content: -```tsx title=src/admin/components/onboarding-flow/orders/order-detail.tsx +```tsx title=src/admin/components/onboarding-flow/default/orders/order-detail.tsx import React from "react" -import IconBadge from "../../shared/icon-badge" -import ComputerDesktopIcon from "../../shared/icons/computer-desktop-icon" -import DollarSignIcon from "../../shared/icons/dollar-sign-icon" +import { + ComputerDesktopSolid, + CurrencyDollarSolid, + ToolsSolid, +} from "@medusajs/icons" +import { IconBadge, Heading, Text } from "@medusajs/ui" -const OrderDetail = () => { +const OrderDetailDefault = () => { return ( <> -

+ You finished the setup guide 🎉 You now have your first order. Feel free to play around with the order management functionalities, such as capturing payment, creating fulfillments, and more. -

-

+ + Start developing with Medusa -

-

- Medusa is a completely customizable commerce solution. We've curated + + + Medusa is a completely customizable commerce solution. We've curated some essential guides to kickstart your development with Medusa. -

-
+ +
-
-
- - - +
+
+
+ + + +
-

+ Start Selling in 3 Steps -

-

- Go live with a backend, an admin, -
and a storefront in three steps. -

+ + + Go live with a backend, an admin, and a storefront by following + these three steps. +
-
-After creating the above components, import them at the top of `src/admin/widgets/onboarding-flow/onboarding-flow.tsx`: +
+ +ProductsListNextjs component + + + +The `ProductsListNextjs` component is used in the first step of the onboarding widget's Next.js flow. It allows the user to create sample products. + +Create the file `src/admin/components/onboarding-flow/nextjs/products/products-list.tsx` with the following content: -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -import ProductsList from "../../components/onboarding-flow/products/products-list" -import ProductDetail from "../../components/onboarding-flow/products/product-detail" -import OrdersList from "../../components/onboarding-flow/orders/orders-list" -import OrderDetail from "../../components/onboarding-flow/orders/order-detail" -``` - -Then, replace the initialization of the `Steps` variable within the `OnboardingFlow` widget with the following: - -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -// TODO add steps -const Steps: Step[] = [ - { - id: "create_product", - title: "Create Product", - component: ProductsList, - onNext: goToProductView, - }, - { - id: "preview_product", - title: "Preview Product", - component: ProductDetail, - onNext: goToOrders, - }, - { - id: "create_order", - title: "Create an Order", - component: OrdersList, - onNext: goToOrderView, - }, - { - id: "setup_finished", - title: "Setup Finished: Start developing with Medusa", - component: OrderDetail, - }, -] -``` - -The next step is to retrieve the current step of the onboarding flow from the Medusa backend. - ---- - -## Step 4: Use Endpoints From Widget - -In this section, you’ll implement the `TODO`s in the `OnboardingFlow` that require communicating with the backend. - -There are different ways you can consume custom backend endpoints. The Medusa React library provides utility methods that allow you to create hooks similar to those available by default in the library. You can then utilize these hooks to send requests to custom backend endpoints. - -Add the following imports at the top of `src/admin/widgets/onboarding-flow/onboarding-flow.tsx`: - -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -import { - useAdminCustomPost, - useAdminCustomQuery, +```tsx title=src/admin/components/onboarding-flow/nextjs/products/products-list.tsx +import React from "react" +import { + useAdminCreateProduct, + useAdminCreateCollection, + useMedusa, } from "medusa-react" -``` +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, Text } from "@medusajs/ui" +import { AdminPostProductsReq, Product } from "@medusajs/medusa" +import getSampleProducts from "../../../../utils/sample-products" +import prepareRegions from "../../../../utils/prepare-region" -Next, add the following at the top of the `OnboardingFlow` component: +const ProductsListNextjs = ({ onNext, isComplete }: StepContentProps) => { + const { mutateAsync: createCollection, isLoading: collectionLoading } = + useAdminCreateCollection() + const { mutateAsync: createProduct, isLoading: productLoading } = + useAdminCreateProduct() + const { client } = useMedusa() -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -const OnboardingFlow = (props: any) => { - const QUERY_KEY = ["onboarding_state"] - const { data, isLoading } = useAdminCustomQuery< - undefined, - OnboardingStateRes - >("/onboarding", QUERY_KEY) - const { mutate } = useAdminCustomPost< - AdminOnboardingUpdateStateReq, - OnboardingStateRes - >("/onboarding", QUERY_KEY) + const isLoading = collectionLoading || productLoading - // ... -} -``` + const createSample = async () => { + try { + const { collection } = await createCollection({ + title: "Merch", + handle: "merch", + }) -Learn more about the available custom hooks such as `useAdminCustomPost` and `useAdminCustomQuery` in the [Medusa React documentation](../medusa-react/overview.mdx#custom-hooks). + const regions = await prepareRegions(client) -`data` now holds the current onboarding state from the backend, and `mutate` can be used to update the onboarding state in the backend. + const tryCreateProduct = async (sampleProduct: AdminPostProductsReq): Promise => { + try { + return (await createProduct(sampleProduct)).product + } catch { + // ignore if product already exists + return null + } + } -After that, replace the declarations within `OnboardingFlow` that had a `TODO` comment with the following: + let product: Product + const sampleProducts = getSampleProducts({ + regions, + collection_id: collection.id, + }) + await Promise.all( + sampleProducts.map(async (sampleProduct, index) => { + const createdProduct = await tryCreateProduct(sampleProduct) + if (index === 0 && createProduct) { + product = createdProduct + } + }) + ) + onNext(product) + } catch (e) { + console.error(e) + } + } -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx -const OnboardingFlow = (props: ExtensionProps) => { - // ... - const currentStep: STEP_ID | undefined = data?.status - ?.current_step as STEP_ID - - if ( - !isLoading && - data?.status?.is_complete && - !localStorage.getItem("override_onboarding_finish") + return ( +
+ + Products is Medusa represent the products you sell. You can set their general details including a + title and description. Each product has options and variants, and you can set a price for each variant. + + + Click the button below to create sample products. + + {!isComplete && ( +
+ +
+ )} +
) - {return null} - - const updateServerState = ( - payload: UpdateOnboardingStateInput, - onSuccess: () => void = () => {} - ) => { - mutate(payload, { onSuccess }) - } - - const onStart = () => { - updateServerState({ current_step: STEP_FLOW[0] }) - navigate(`/a/products`) - } - - const setStepComplete = ({ - step_id, - extraData, - onComplete, - }: { - step_id: STEP_ID; - extraData?: UpdateOnboardingStateInput; - onComplete?: () => void; - }) => { - const next = STEP_FLOW[ - STEP_FLOW.findIndex((step) => step === step_id) + 1 - ] - updateServerState({ - current_step: next, - ...extraData, - }, onComplete) - } - - // ... } + +export default ProductsListNextjs ``` -`currentStep` now holds the current step retrieve from the backend; `updateServerState` updates the current step in the backend; `onStart` updates the current step in the backend to the first step; and `setStepComplete` completes the current step by updating the current step in the backend to the following step. +
-Finally, in the returned JSX, update the `TODO` in the `` component to pass the component the necessary `data`: +
+ +ProductDetailNextjs component -```tsx title=src/admin/widgets/onboarding-flow/onboarding-flow.tsx - + + +The `ProductDetailNextjs` component is used in the second step of the onboarding's Next.js flow. It shows the user a button to preview the product created in the first step using the Next.js starter. + +Create the file `src/admin/components/onboarding-flow/nextjs/products/product-detail.tsx` with the following content: + + + +```tsx title=src/admin/components/onboarding-flow/nextjs/products/product-detail.tsx +import { useAdminProduct } from "medusa-react" +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, Text } from "@medusajs/ui" + +const ProductDetailNextjs = ({ onNext, isComplete, data }: StepContentProps) => { + const { product, isLoading: productIsLoading } = useAdminProduct(data?.product_id) + return ( +
+
+ + We have now created a few sample products in your Medusa store. You can scroll down to see what the Product Detail view looks like in the Admin dashboard. + This is also the view you use to edit existing products. + + + To view the products in your store, you can visit the Next.js Storefront that was installed with create-medusa-app. + + + The Next.js Storefront Starter is a template that helps you start building an ecommerce store with Medusa. + You control the code for the storefront and you can customize it further to fit your specific needs. + + + Click the button below to view the products in your Next.js Storefront. + + + Having trouble? Click{" "} + + here + . + +
+
+ + + + {!isComplete && ( + + )} +
+
+ ) +} + +export default ProductDetailNextjs ``` +
+ +
+ +OrdersListNextjs component + + + +The `OrdersListNextjs` component is used in the third step of the onboarding's Next.js flow. It links the user to the checkout flow in the Next.js storefront so that they can create an order. + +Create the file `src/admin/components/onboarding-flow/nextjs/orders/orders-list.tsx` with the following content: + + + +```tsx title=src/admin/components/onboarding-flow/nextjs/orders/orders-list.tsx +import React from "react" +import { + useAdminProduct, + useCreateCart, + useMedusa, +} from "medusa-react" +import { StepContentProps } from "../../../../widgets/onboarding-flow/onboarding-flow" +import { Button, Text } from "@medusajs/ui" +import prepareRegions from "../../../../utils/prepare-region" +import prepareShippingOptions from "../../../../utils/prepare-shipping-options" + +const OrdersListNextjs = ({ isComplete, data }: StepContentProps) => { + const { product } = useAdminProduct(data.product_id) + const { mutateAsync: createCart, isLoading: cartIsLoading } = useCreateCart() + const { client } = useMedusa() + + const prepareNextjsCheckout = async () => { + const variant = product.variants[0] ?? null + try { + const regions = await prepareRegions(client) + await prepareShippingOptions(client, regions[0]) + const { cart } = await createCart({ + region_id: regions[0]?.id, + items: [ + { + variant_id: variant?.id, + quantity: 1, + }, + ], + }) + + window.open(`http://localhost:8000/checkout?cart_id=${cart?.id}&onboarding=true`, "_blank") + } catch (e) { + console.error(e) + } + } + + return ( + <> +
+ + The last step is to create a sample order using one of your products. You can then view your order’s details, process its payment, fulfillment, inventory, and more. + + + You can use the button below to experience hand-first the checkout flow in the Next.js storefront. After placing the order in the storefront, you’ll be directed back here to view the order’s details. + +
+
+ {!isComplete && ( + <> + + + )} +
+ + ) +} + +export default OrdersListNextjs +``` + +
+ +
+ +OrderDetailNextjs component + + + +The `OrderDetailNextjs` component is used in the fourth and final step of the onboarding's default flow. It educates the user on the next steps when developing with Medusa. + +Create the file `src/admin/components/onboarding-flow/nextjs/orders/order-detail.tsx` with the following content: + + + +```tsx title=src/admin/components/onboarding-flow/nextjs/orders/order-detail.tsx +import React from "react" +import { CurrencyDollarSolid, NextJs, SquaresPlusSolid } from "@medusajs/icons" +import { IconBadge, Heading, Text } from "@medusajs/ui" + +const OrderDetailNextjs = () => { + const queryParams = `?ref=onboarding&type=${ + process.env.MEDUSA_ADMIN_ONBOARDING_TYPE || "nextjs" + }` + return ( + <> + + You finished the setup guide 🎉. You have now a complete ecommerce store + with a backend, admin, and a Next.js storefront. Feel free to play + around with each of these components to experience all commerce features + that Medusa provides. + + + Continue Building your Ecommerce Store + + + Your ecommerce store provides all basic ecommerce features you need to + start selling. You can add more functionalities, add plugins for + third-party integrations, and customize the storefront’s look and feel + to support your use case. + + +
+ You can find more useful guides in{" "} + + our documentation + + . If you like Medusa, please{" "} + + star us on GitHub + + . +
+ + ) +} + +export default OrderDetailNextjs +``` +
+ --- -## Step 5: Test it Out +## Step 4: Test it Out You’ve now implemented everything necessary for the onboarding flow! You can test it out by building the changes and running the `develop` command: diff --git a/www/apps/docs/content/admin/routes.md b/www/apps/docs/content/admin/routes.md index e1abffc919..4efc526e92 100644 --- a/www/apps/docs/content/admin/routes.md +++ b/www/apps/docs/content/admin/routes.md @@ -356,9 +356,9 @@ const CustomPage = () => { export default CustomPage ``` -### Custom Endpoints +### Custom API Routes -You can also use `medusa-react` to interact with custom endpoints using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks). +You can also use `medusa-react` to interact with custom API Routes using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks). --- diff --git a/www/apps/docs/content/admin/setting-pages.md b/www/apps/docs/content/admin/setting-pages.md index 0f923beb04..acb20896ca 100644 --- a/www/apps/docs/content/admin/setting-pages.md +++ b/www/apps/docs/content/admin/setting-pages.md @@ -337,9 +337,9 @@ export const config: SettingConfig = { export default CustomSettingPage ``` -### Custom Endpoints +### Custom API Routes -You can also use `medusa-react` to interact with custom endpoints using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks). +You can also use `medusa-react` to interact with custom API Routes using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks). --- diff --git a/www/apps/docs/content/admin/widgets.md b/www/apps/docs/content/admin/widgets.md index 1c54706925..93c18718cf 100644 --- a/www/apps/docs/content/admin/widgets.md +++ b/www/apps/docs/content/admin/widgets.md @@ -1270,9 +1270,9 @@ export const config: WidgetConfig = { export default ProductWidget ``` -### Custom Endpoints +### Custom API Routes -You can also use `medusa-react` to interact with custom endpoints using the [createCustomAdminHooks utility function](../medusa-react/overview.mdx#custom-hooks). +You can also use `medusa-react` to interact with custom API Routes using the [createCustomAdminHooks utility function](../medusa-react/overview.mdx#custom-hooks). --- diff --git a/www/apps/docs/content/contribution/docs.md b/www/apps/docs/content/contribution/docs.md index fd0d0e7949..6235bdedfd 100644 --- a/www/apps/docs/content/contribution/docs.md +++ b/www/apps/docs/content/contribution/docs.md @@ -50,7 +50,7 @@ Documentation pages under the `www/apps/docs/content/references` directory are g The API reference's content is split into two types: 1. Static content, which are the content related to getting started, expanding fields, and more. These are located in the [www/apps/api-reference/app/_mdx](https://github.com/medusajs/medusa/tree/develop/www/apps/api-reference/app/_mdx) directory. They are MDX files. -2. OpenAPI specs that are shown to developers when checking the reference of an endpoint. These are automatically generated from comments on endpoints. So, if you find issues in them or want to make improvements, you have to find the endpoint under the [`packages/medusa/src/api`](https://github.com/medusajs/medusa/tree/develop/packages/medusa/src/api) directory and make changes to its comments. +2. OpenAPI specs that are shown to developers when checking the reference of an API Route. These are automatically generated from comments on API Routes. So, if you find issues in them or want to make improvements, you have to find the API Routes under the [`packages/medusa/src/api`](https://github.com/medusajs/medusa/tree/develop/packages/medusa/src/api) directory and make changes to its comments. ### Medusa UI Documentation diff --git a/www/apps/docs/content/deployments/server/deploying-on-microtica.md b/www/apps/docs/content/deployments/server/deploying-on-microtica.md index 7a8200cc93..e3af825c88 100644 --- a/www/apps/docs/content/deployments/server/deploying-on-microtica.md +++ b/www/apps/docs/content/deployments/server/deploying-on-microtica.md @@ -100,7 +100,7 @@ Once the build process is complete, a new deployment with the infrastructure res ## Test the Backend -After the deployment is finished, navigate to Resources → [AppName] (Medusa in this example) → Overview. Then, under the Resource Outputs section you should see the "AccessUrl". This is the backend's URL that you can use to access API endpoints and test them. You can try getting the list of products using the endpoint `/store/products`. +After the deployment is finished, navigate to Resources → [AppName] (Medusa in this example) → Overview. Then, under the Resource Outputs section you should see the "AccessUrl". This is the backend's URL that you can use to access API Routes and test them. You can try getting the list of products using the API Route `/store/products`. ### Health Route diff --git a/www/apps/docs/content/development/endpoints/add-middleware.mdx b/www/apps/docs/content/development/api-routes/add-middleware-express-route.mdx similarity index 96% rename from www/apps/docs/content/development/endpoints/add-middleware.mdx rename to www/apps/docs/content/development/api-routes/add-middleware-express-route.mdx index 496b77d2e3..d58145eb4c 100644 --- a/www/apps/docs/content/development/endpoints/add-middleware.mdx +++ b/www/apps/docs/content/development/api-routes/add-middleware-express-route.mdx @@ -1,5 +1,4 @@ --- -description: 'Learn how to add a middleware in Medusa. A middleware is a function that has access to the request and response objects and can be used to perform actions around an endpoint.' addHowToData: true --- @@ -7,10 +6,16 @@ import Troubleshooting from '@site/src/components/Troubleshooting' import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md' import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md' -# Middlewares +# Middlewares - Express Endpoints Approach In this document, you’ll learn how to add a middleware to an existing or custom route in Medusa. +:::note + +Following v1.17.2 of `@medusajs/medusa`, it's highly recommended to use the [middlewares.ts file](./add-middleware.mdx) to create middlewares instead. Future versions of Medusa may drop support of this approach. + +::: + ## Overview As the Medusa backend is built on top of [Express](https://expressjs.com/), Express’s features can be utilized during your development with Medusa. diff --git a/www/apps/docs/content/development/api-routes/add-middleware.mdx b/www/apps/docs/content/development/api-routes/add-middleware.mdx new file mode 100644 index 0000000000..e1493c7d4e --- /dev/null +++ b/www/apps/docs/content/development/api-routes/add-middleware.mdx @@ -0,0 +1,214 @@ +--- +addHowToData: true +--- + +import Troubleshooting from '@site/src/components/Troubleshooting' +import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md' +import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md' + +# Middlewares + +In this document, you’ll learn how to add a middleware to existing or custom API Routes in Medusa. + +:::tip + +v1.17.2 of `@medusajs/medusa` introduced a new approach to creating middlewares using a single `middlewares.ts` file. You can still use the [Express Router Approach](./add-middleware-express-route.mdx), however, it's highly recommended that you start using this new approach. + +::: + +## Basic Implementation + +```ts title=src/api/middlewares.ts +import type { MiddlewaresConfig } from "@medusajs/medusa" +import type { + MedusaNextFunction, + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +const storeMiddleware = ( + req: MedusaRequest, + res: MedusaResponse, + next: MedusaNextFunction +) => { + // do something + next() +} + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/*", + middlewares: [storeMiddleware], + }, + ], +} +``` + +A middleware is a function that has access to the `MedusaRequest` and `MedusaResponse` objects that are passed to API Route method handlers. + +Middlewares are used to perform an action when a request is sent to an API Route, or modify the response of an API route, among other usages. + +### middlewares.ts File + +Middlewares are defined in the `src/api/middlewares.ts` file. This file must expose a config object of type `MiddlewaresConfig` imported from `@medusajs/medusa`. + +This object accepts a parameter `routes`, whose value is an array of middleware route objects. Each middleware route object accepts the following properties: + +- The `matcher` property accepts a string or a regular expression that will be used to check whether the middlewares should be applied on a API Routes. +- The `middlewares` property is an array of middlewares that should be applied on API Routes matching the pattern specified in `matcher`. + +--- + +## Build Files + +Similar to custom API Routes, you must transpile the files under `src` into the `dist` directory for the backend to load them. + +To do that, run the following command before running the Medusa backend: + +```bash npm2yarn +npm run build +``` + +You can then test that the middleware is working by running the backend. + +--- + +## Register New Resources in Dependency Container + +In some cases, you may need to register a resource to use within your commerce application. For example, you may want to register the logged-in user to access it in other resources, such as services. You can do that in your middleware. + +:::tip + +If you want to register a logged-in user and access it in your resources, you can check out [this example guide](./example-logged-in-user.mdx). + +::: + +To register a new resource in the dependency container, use the `MedusaRequest` object's `scope.register` method. It accepts an object, where each key is the name to be registered in the dependency container, and its value is an object that has a `resolve` property. + +The `resolve`'s value is a function that returns the resource to be registered in the dependency container. + +For example: + +```ts title=src/api/middlewares.ts +import type { MiddlewaresConfig } from "@medusajs/medusa" +import type { + MedusaNextFunction, + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +const customResource = ( + req: MedusaRequest, + res: MedusaResponse, + next: MedusaNextFunction) => { + req.scope.register({ + customResource: { + resolve: () => "my custom resource", + }, + }) + + next() +} + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/*", + middlewares: [customResource], + }, + ], +} +``` + +You can then load this new resource within other resources. For example, to load it in a service: + + + +```ts title=src/services/custom-service.ts +import { TransactionBaseService } from "@medusajs/medusa" + +class CustomService extends TransactionBaseService { + + constructor(container, options) { + super(...arguments) + + // use the registered resource. + try { + container.customResource + } catch (e) { + // avoid errors when the backend first loads + } + } +} + +export default CustomService +``` + +:::note + +Make sure to wrap your usage of the new resource in a try-catch block when you use it in a constructor. This is to avoid errors that can arise when the backend first loads, as the resource isn't registered yet. + +::: + +### Note About Services Lifetime + +If you want to access new registrations in the dependency container within a service, you must set the lifetime of the service either to `Lifetime.SCOPED` or `Lifetime.TRANSIENT`. Services that have a `Lifetime.SINGLETON` lifetime can't access new registrations since they're resolved and cached in the root dependency container beforehand. You can learn more in the [Create Services documentation](../services/create-service.mdx#service-life-time). + +For custom services, no additional action is required as the default lifetime is `Lifetime.SCOPED`. However, if you extend a core service, you must change the lifetime since the default lifetime for core services is `Lifetime.SINGLETON`. + +For example: + + + +```ts +import { Lifetime } from "awilix" +import { + ProductService as MedusaProductService, +} from "@medusajs/medusa" + +// extending ProductService from the core +class ProductService extends MedusaProductService { + // The default life time for a core service is SINGLETON + static LIFE_TIME = Lifetime.SCOPED + + constructor(container, options) { + super(...arguments) + + // use the registered resource. + try { + container.customResource + } catch (e) { + // avoid errors when the backend first loads + } + } + + // ... +} + +export default ProductService +``` + +--- + +## Troubleshooting + + + }, + { + title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)', + content: + } + ]} +/> + +--- + +## See Also + +- [Store API reference](https://docs.medusajs.com/api/store) +- [Admin API reference](https://docs.medusajs.com/api/admin) diff --git a/www/apps/docs/content/development/endpoints/create.mdx b/www/apps/docs/content/development/api-routes/create-express-route.mdx similarity index 96% rename from www/apps/docs/content/development/endpoints/create.mdx rename to www/apps/docs/content/development/api-routes/create-express-route.mdx index f2135696c7..3fb5dc49a4 100644 --- a/www/apps/docs/content/development/endpoints/create.mdx +++ b/www/apps/docs/content/development/api-routes/create-express-route.mdx @@ -1,22 +1,19 @@ --- -description: 'Learn how to create endpoints in Medusa. This guide also includes how to add CORS configurations, creating multiple endpoints, adding protected routes, and more.' addHowToData: true --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; -# How to Create Endpoints +# Create Express Endpoint -In this document, you’ll learn how to create endpoints in Medusa. +In this document, you’ll learn how to create express endpoints in Medusa. -## Overview +:::note -Custom endpoints are created under the `src/api` directory in your Medusa Backend. They're defined in a TypeScript or JavaScript file named `index` (for example, `index.ts`). This file should export a function that returns an Express router or an array of routes and middlewares. +Following v1.17.2 of `@medusajs/medusa`, it's highly recommended to use the [API Routes](./create.mdx) instead. Future versions of Medusa may drop support of Express Endpoints. -To consume the custom endpoints in your Medusa backend, you must transpile them with the `build` command before starting your backend. - ---- +::: ## Basic Implementation @@ -61,7 +58,7 @@ npm run build ## Defining Multiple Routes or Middlewares -Instead of returning an Express router in the function, you can return an array of routes and [middlewares](./add-middleware.mdx). +Instead of returning an Express router in the function, you can return an array of routes and [middlewares](./add-middleware-express-route.mdx). For example: @@ -419,7 +416,7 @@ export default (rootDirectory) => { As Medusa uses v4 of Express, you need to manually handle errors thrown asynchronously as explained in [Express's documentation](https://expressjs.com/en/guide/error-handling.html). -You can use [middlewares](./add-middleware.mdx) to handle errors. You can also use middlewares defined by Medusa, which ensure that your error handling is consistent across your Medusa backend. +You can use [middlewares](./add-middleware-express-route.mdx) to handle errors. You can also use middlewares defined by Medusa, which ensure that your error handling is consistent across your Medusa backend. :::note diff --git a/www/apps/docs/content/development/api-routes/create.mdx b/www/apps/docs/content/development/api-routes/create.mdx new file mode 100644 index 0000000000..892002d519 --- /dev/null +++ b/www/apps/docs/content/development/api-routes/create.mdx @@ -0,0 +1,744 @@ +--- +addHowToData: true +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# How to Create an API Route + +In this document, you’ll learn how to create API Routes in Medusa. + +:::tip + +v1.17.2 of `@medusajs/medusa` introduced API Routes to replace Express endpoints. You can still use the [Express endpoints approach](./create-express-route.mdx), however, it's highly recommended that you start using API Routes. + +::: + +## Basic Implementation + +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const GET = ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "[GET] Hello world!", + }) +} + +export const POST = ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "[POST] Hello world!", + }) +} +``` + +### API Route Path + +Custom API Routes must be created in a file named `route.ts` or `route.js` under the `src/api` directory of your Medusa backend or plugin. The API Route's path will be the same as the path of its corresponding `route.ts` file relative to `src/api`. + +For example, if you're creating the API route `store/custom`, you must create the file `src/api/store/custom/route.ts`. + +### API Route Method + +`route.ts` can export at least one of the following method handler functions: `GET`, `POST`, `DELETE`, `PUT`, `PATCH`, `OPTIONS`, and `HEAD`. Defining these method handlers adds a new API Route for the corresponding HTTP method at the same path. + +Each of these method handler functions receives two parameters: the `MedusaRequest` which extends Express's [Request](https://expressjs.com/en/api.html#req), and the `MedusaResponse` which extends [Response](https://expressjs.com/en/api.html#res). Both are imported from `@medusajs/medusa`. + +In the example above, `GET` and `POST` API Routes will be added at the `store/custom` path. + +--- + +## Building Files + +Custom API Routes must be transpiled and moved to the `dist` directory before you can start consuming them. When you run your backend using either the `medusa develop` or `npx medusa develop` commands, it watches the files under `src` for any changes, then triggers the `build` command and restarts the server. + +However, the build isn't triggered when the backend first starts running, and it's never triggered when the `medusa start` or `npx medusa start` commands are used. + +So, make sure to run the `build` command before starting the backend and testing out your API Routes: + +```bash npm2yarn +npm run build +``` + +--- + +## Medusa API Routes Path Convention + +Although your API Route can be under any path you wish, the Medusa backend uses the following conventions: + +- All storefront REST APIs are prefixed by `/store`. For example, the `/store/products` API Route lets you retrieve the products to display them on your storefront. +- All admin REST APIs are prefixed by `/admin`. For example, the `/admin/products` API Route lets you retrieve the products to display them on your admin. + +--- + +## Path Parameters + +If your API Route accepts a path parameter, you can place its route file inside a directory with the name `[]`, where `` is the name of your parameter. + +For example, to add an API Route at the path `store/custom/[id]`, create the route file at `src/api/store/custom/[id]/route.ts`. + +You can access a path parameter's value in method handlers using the `MedusaRequest` object's `params` property, which is an object. Each of the `params` keys is a path parameter's name, and its value is the supplied value when sending the request to the API route. + +For example: + +```ts title=src/api/store/custom/[id]/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export function GET( + req: MedusaRequest, + res: MedusaResponse +) { + const id = req.params.id + + // do something with the ID. +} +``` + +An API Route can have more than one path parameter, but each path parameter's nam is unique. If the same path parameter name is used more than once in the same route path, it results in an error and the Medusa Backend won't register the API Route. + +For example, if your API route accepts an author ID and a post ID, the path to your route file can be `src/api/author/[id]/posts/[post_id]/route.ts`. You can then use the `MedusaRequest` object's `params.id` and `params.post_id` to access the values of the path parameters. + +--- + +## CORS Configuration + +CORS configurations are automatically added to custom API Routes defined under the `/store` or `/admin` path prefixes based on the [store_cors and admin_cors configurations](../backend/configurations.md#admin_cors-and-store_cors) respectively. + +To add CORS configurations to custom API routes under other path prefixes, or override the CORS configurations added by default, define a [middleware](./add-middleware.mdx) on your API routes and pass it the `cors` middleware. For example: + +```ts title=src/api/middlewares.ts +import type { + MiddlewaresConfig, +} from "@medusajs/medusa" +import cors from "cors" + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/custom/*", + middlewares: [ + cors({ + origin: "*", + credentials: true, + }), + ], + }, + ], +} +``` + +--- + +## Parse Request Body Parameters + +By default, the Medusa backend parses the body of all requests sent to your API Routes with the `Content-Type` header set to `application/json` to a JavaScript object. Then, the parsed data is attached to the `MedusaRequest` object's `body` property, which is an object. + +Each of the `body`'s keys are a name of the request body parameters, and its value is the passed value in the request body. + +For example: + +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const POST = ( + req: MedusaRequest, + res: MedusaResponse +) => { + const name = req.body.name + + // do something with the data... +} +``` + +If you want to parse other content types, such as `application/x-www-form-urlencoded`, you have to add a [middleware](./add-middleware.mdx) to your API routes that parses that body type. + +For example: + +```ts title=src/api/middlewares.ts +import type { + MiddlewaresConfig, +} from "@medusajs/medusa" +import { + urlencoded, +} from "body-parser" + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/*", + middlewares: [ + urlencoded({ extended: true }), + ], + }, + ], +} +``` + +Note that the `urlencoded` middleware imported from the [body-parser package](https://www.npmjs.com/package/body-parser) attaches the parsed data to the `MedusaRequest` object's `body` property as well. + +--- + +## Protected API Routes + +Protected API routes are routes that should only be accessible by logged-in customers or users. + +### Protect Store API Routes + +By default, API routes prefixed by `/store` don't require customer authentication to access the API route. However, you can still access the logged-in customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`, which will be `undefined` if the customer isn't logged in. + +For example: + +```ts title=src/api/store/custom/route.ts +import { CustomerService } from "@medusajs/medusa" +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const id = req.user.customer_id + + if (!id) { + // TODO handle not logged in + // customers based on the custom + // API route's functionality + } + + const customerService = req.scope.resolve( + "customerService" + ) + + const customer = await customerService.retrieve(id) + + // ... +} +``` + +API Routes prefixed by `/store/me`, on the other hand, require customer authentication to access the API Route. You can access the logged-in customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`. + +If you want to disable authentication requirement on your custom API Route prefixed with `/store/me`, export an `AUTHENTICATE` variable in the route file with its value set to `false`. For example: + +```ts title=src/api/store/me/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "Hello", + }) +} + +export const AUTHENTICATE = false +``` + +:::note + +This disables authentication requirement on all API Route methods defined in the same file. + +::: + +### Protect Admin API Routes + +By default, all API Routes prefixed by `/admin` require admin user authentication to access the API Route. You can access the logged-in user's ID in the API Route method handler using the `MedusaRequest` object's `user.userId`. + +For example: + +```ts title=src/api/admin/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, + UserService, +} from "@medusajs/medusa" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const id = req.user.userId + + const userService = req.scope.resolve( + "userService" + ) + + const user = await userService.retrieve(id) + + // ... +} +``` + +To disable authentication requirement on an admin API Route, export an `AUTHENTICATE` variable in your route file with its value set to `false`. + +For example: + +```ts title=src/api/admin/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "Hello", + }) +} + +export const AUTHENTICATE = false +``` + +:::note + +This disables authentication requirement on all API Route methods defined in the same file. + +::: + +### Protect Other API Routes + +To protect API routes that aren't prefixed with `/store` or `/admin`, you can use one of the following middlewares exported by `@medusajs/medusa` for authenticating customers or users: + +- `authenticate`: this middleware ensures that only authenticated admin users can access an API Route. You can access the user's ID in the API Route method handler using the `MedusaRequest` object's `user.userId`. +- `authenticateCustomer`: this middleware doesn't require a customer to be authenticated, but if a customer is logged in, it attaches their ID to the `MedusaRequest` object's `user.customer_id`. +- `requireCustomerAuthentication`: this middleware ensures that only authenticated customers can access an API Route. You can access the customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`. + +For example: + +```ts title=src/api/middlewares.ts +import { + authenticate, + requireCustomerAuthentication, + type MiddlewaresConfig, +} from "@medusajs/medusa" + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/custom/admin*", + middlewares: [authenticate()], + }, + { + matcher: "/custom/customer*", + middlewares: [requireCustomerAuthentication()], + }, + ], +} +``` + +--- + +## Retrieve Medusa Config + +You can access the configurations exported in `medusa-config.js`, including your custom configurations, by resolving the `configModule` resource using [dependency injection](../fundamentals/dependency-injection.md). + +For example: + +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { ConfigModule } from "@medusajs/medusa" + +// This is only helpful if you're +// accessing custom configurations +// otherwise it's fine to just use `ConfigModule` +type MyConfigModule = ConfigModule & { + projectConfig: { + custom_config?: string + } +} + +export const GET = ( + req: MedusaRequest, + res: MedusaResponse +) => { + const configModule = req.scope.resolve( + "configModule" + ) + res.json({ + message: configModule.projectConfig.custom_config, + }) +} +``` + +--- + +## Handle Errors + +Medusa provides an `errorHandler` middleware that you can use on your custom API Routes so that your error handling is consistent with the Medusa backend. You can also create custom [middlewares](./add-middleware.mdx) to handle errors. + +To handle errors using Medusa's middlewares, first, import the `errorHandler` middleware from `@medusajs/medusa` and apply it on your routes. + +For example: + +```ts title=src/api/middlewares.ts +import { + errorHandler, + type MiddlewaresConfig, +} from "@medusajs/medusa" + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/custom*", + middlewares: [errorHandler()], + }, + ], +} +``` + +Make sure it's applied after all other middlewares. + +Then, wrap the method handler function of every API route method with the `wrapHandler` function imported from `@medusajs/medusa`. For example: + +```ts title=src/api/store/custom/route.ts +import { + MedusaRequest, + MedusaResponse, + wrapHandler, +} from "@medusajs/medusa" + +export const GET = wrapHandler(async ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "[GET] Hello world!", + }) +}) + +export const POST = wrapHandler(async ( + req: MedusaRequest, + res: MedusaResponse +) => { + res.json({ + message: "[POST] Hello world!", + }) +}) +``` + +Now all errors thrown in your custom API Routes, or in resources you use within your API Route such as services, are caught and returned to the user. + +### Using MedusaError + +If you throw errors like this: + +```ts +throw new Error ("Post was not found") +``` + +The API Route returns the following object error in the response: + +```json +{ + "code": "unknown_error", + "type": "unknown_error", + "message": "An unknown error occurred." +} +``` + +To ensure your error message is relayed in the response, it's recommended to use `MedusaError` imported from `@medusajs/utils` as the thrown error instead. + +For example: + +```ts +import { MedusaError } from "@medusajs/utils" + +// ... + +throw new MedusaError( + MedusaError.Types.NOT_FOUND, + "Post was not found" +) +``` + +The constructor of `MedusaError` accepts the following parameters: + +1. The first parameter is the error's type. You can use one of the predefined errors under `MedusaError.Types`, such as `MedusaError.Types.NOT_FOUND` which sets the response status code to `404` automatically. +2. The second parameter is the message of the error. +3. The third parameter is an optional code, which is a string, that's returned in the error object. + +After using `MedusaError`, the returned error in the response provides a clearer message: + +```json +{ + "type": "not_found", + "message": "Post was not found" +} +``` + +--- + +## Use Other Resources + +Resources, such as services, that are registered in the [dependency container](../fundamentals/dependency-injection.md) can be retrieved in an API Route's handler method using the `MedusaRequest` object's `scope.resolve` method. + +The `scope` method accepts as a parameter the resource's registration name in the [dependency container](../fundamentals/dependency-injection.md). + +### Example: Retrieve Repository + +:::tip + +Posts are represented by a custom entity not covered in this guide. You can refer to the [entities](../entities/create.mdx#adding-relations) for more details on how to create a custom entity. + +::: + +```ts title=src/api/store/posts/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { + PostRepository, +} from "../../../repositories/post" +import { EntityManager } from "typeorm" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postRepository = + req.scope.resolve("postRepository") + const manager = req.scope.resolve("manager") + const postRepo = manager.withRepository(postRepository) + + res.json({ + posts: await postRepo.find(), + }) +} +``` + +Notice that to retrieve an instance of the repository, you need to retrieve first Typeorm's Entity Manager from the dependency container, then use its `withRepository` method. + +### Example: Retrieve Service + +:::note + +`PostService` is a custom service that is not covered in this guide. You can refer to the [services](../services/create-service.mdx) documentation for more details on how to create a custom service, and find an [example of PostService](../services/create-service.mdx#example-services-with-crud-operations) + +::: + +```ts title=src/api/store/posts/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { PostService } from "../../../services/post" + +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + res.json({ + posts: await postService.list(), + }) +} +``` + +--- + +## Ignored Files and Directories + +Files and directories prefixed with `_` are ignored. This can be helpful if you want to implement API Route method handlers in different files, then reference them in your `route.ts` file. + +For example: + + + + +```ts +import getProducts from "../_methods/get-products" + +export const GET = getProducts +``` + + + + +```ts +import { + MedusaRequest, + MedusaResponse, + ProductService, +} from "@medusajs/medusa" + +export default async function ( + req: MedusaRequest, + res: MedusaResponse +) { + const productService = req.scope.resolve( + "productService" + ) + + const products = await productService.list({}) + + res.json({ + products, + }) +} +``` + + + + +--- + +## Example: CRUD API Routes + +This section provides an example of creating API Routes that perform Create, Read, Update, and Delete (CRUD) operations. + +:::note + +You can refer to the [Entities](../entities/create.mdx#adding-relations) and [Services](../services/create-service.mdx#example-services-with-crud-operations) documentation to learn how to create the custom entities and services used in this example. + +::: + + + + +```ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { PostService } from "../../../services/post" + +// list posts +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + res.json({ + posts: await postService.list(), + }) +} + +// create a post +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + // basic validation of request body + if (!req.body.title || !req.body.author_id) { + throw new Error("`title` and `author_id` are required.") + } + + const post = await postService.create(req.body) + + res.json({ + post, + }) +} +``` + + + + +```ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { PostService } from "../../../services/post" + +// retrieve a post by its ID +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + const post = await postService.retrieve(req.params.id) + + res.json({ + post, + }) +} + +// update a post by its ID +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + // basic validation of request body + if (req.body.id) { + throw new Error("Can't update post ID") + } + + const post = await postService.update( + req.params.id, + req.body + ) + + res.json({ + post, + }) +} + +// delete a post by its ID +export const DELETE = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postService: PostService = req.scope.resolve( + "postService" + ) + + await postService.delete(req.params.id) + + res.status(200).end() +} +``` + + + + +--- + +## See Also + +- [Storefront API Reference](https://docs.medusajs.com/api/store) +- [Admin API Reference](https://docs.medusajs.com/api/admin) diff --git a/www/apps/docs/content/development/api-routes/example-logged-in-user.mdx b/www/apps/docs/content/development/api-routes/example-logged-in-user.mdx new file mode 100644 index 0000000000..548f43f08b --- /dev/null +++ b/www/apps/docs/content/development/api-routes/example-logged-in-user.mdx @@ -0,0 +1,171 @@ +--- +addHowToData: true +--- + +import Troubleshooting from '@site/src/components/Troubleshooting' +import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md' +import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md' + +# Example: Access Logged-In User + +This document gives an example of how you can use middlewares to register the logged-in user in the dependency container of your commerce application. You can then access the logged-in user in other resources, such as services. + +:::tip + +You can apply the same steps if you want to register the current customer. + +::: + +Learn more about [middlewares in its guide](./add-middleware.mdx). + +## Step 1: Create the Middleware + +Create the file `src/api/middlewares.ts` with the following content: + +```ts title=src/api/middlewares.ts +import type { + MiddlewaresConfig, + User, + UserService, +} from "@medusajs/medusa" +import type { + MedusaNextFunction, + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +const registerLoggedInUser = async ( + req: MedusaRequest, + res: MedusaResponse, + next: MedusaNextFunction +) => { + let loggedInUser: User | null = null + + if (req.user && req.user.userId) { + const userService = + req.scope.resolve("userService") as UserService + loggedInUser = await userService.retrieve(req.user.userId) + } + + req.scope.register({ + loggedInUser: { + resolve: () => loggedInUser, + }, + }) + + next() +} + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/admin/products", + middlewares: [registerLoggedInUser], + }, + ], +} +``` + +This creates a `registerLoggedInUser` middleware that handles registering the logged-in user in the dependency container. + +It then applies this middleware on the `/admin/products` API Route. You can change that to be the route of any other API Route or a pattern that matches multiple routes. + +--- + +## Step 2: Use in a Service + +Access the logged-in user resource in the constructor of a service: + + + +```ts +import { Lifetime } from "awilix" +import { + TransactionBaseService, + User, +} from "@medusajs/medusa" + +class HelloService extends TransactionBaseService { + + protected readonly loggedInUser_: User | null + + constructor(container, options) { + super(...arguments) + + try { + this.loggedInUser_ = container.loggedInUser + } catch (e) { + // avoid errors when backend first runs + } + } + + // ... +} + +export default HelloService +``` + +If you're accessing it in an extended core service, it’s important to change the lifetime of the service to `Lifetime.SCOPED`. For example: + + + +```ts +import { Lifetime } from "awilix" +import { + ProductService as MedusaProductService, + User, +} from "@medusajs/medusa" + +// extend core product service +class ProductService extends MedusaProductService { + // The default life time for a core service is SINGLETON + static LIFE_TIME = Lifetime.SCOPED + + protected readonly loggedInUser_: User | null + + constructor(container, options) { + super(...arguments) + + this.loggedInUser_ = container.loggedInUser + } +} + +export default ProductService +``` + +You can learn more about the importance of changing the service lifetime in the [Middlewares documentation](./add-middleware.mdx#note-about-services-lifetime). + +--- + +## Step 3: Test it Out + +To test out your implementation, run the following command in the root directory of the Medusa backend to transpile your changes: + +```bash npm2yarn +npm run build +``` + +Then, run your backend with the following command: + +```bash npm2yarn +npx medusa develop +``` + +If you try accessing the API Routes you added the middleware to, you should see your implementation working as expected. + +--- + +## Troubleshooting + + + }, + { + title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)', + content: + } + ]} +/> diff --git a/www/apps/docs/content/development/endpoints/extend-validator.md b/www/apps/docs/content/development/api-routes/extend-validator.md similarity index 61% rename from www/apps/docs/content/development/endpoints/extend-validator.md rename to www/apps/docs/content/development/api-routes/extend-validator.md index 043be82e37..8ecf686fd9 100644 --- a/www/apps/docs/content/development/endpoints/extend-validator.md +++ b/www/apps/docs/content/development/api-routes/extend-validator.md @@ -1,21 +1,20 @@ --- -description: 'Learn how to extend a validator. This is useful when you want to pass additional data to endpoints in the Medusa core.' addHowToData: true --- -# How to Extend an Endpoint Validator +# How to Extend an API Route Validator -In this guide, you'll learn how to extend an endpoint validator from the Medusa core. +In this guide, you'll learn how to extend an API Route validator from the Medusa core. ## Overview -Request fields passed to endpoints that are defined in the Medusa core are validated to ensure that only expected fields are passed, and the passed fields are of correct types. +Request fields passed to API Routes defined in the Medusa core are validated to ensure that only expected fields are passed, and the passed fields are of correct types. -In some scenarios, you may need to allow passing custom fields into an existing endpoint. If a custom field is passed to an endpoint in the core, the endpoint returns an error in the response. +In some scenarios, you may need to allow passing custom fields into an existing API Route. If a custom field is passed to an API Route in the core, the API Route returns an error in the response. -To allow passing custom fields into core endpoints, you must extend Validators. Validators are classes that are used by the core to validate the request parameters to an endpoint. +To allow passing custom fields into core API Routes, you must extend Validators. Validators are classes that are used by the core to validate the request parameters to an API Route. -This guide explains how to extend a validator to allow passing custom fields to an endpoint. You'll be extending the validator of the admin API Create Product endpoint as an example. +This guide explains how to extend a validator to allow passing custom fields to an API Route. You'll be extending the validator of the admin API Create Product route as an example. --- @@ -59,13 +58,13 @@ registerOverriddenValidators(AdminPostProductsReq) In this code snippet you: 1. Import the `registerOverriddenValidators` function from the `@medusajs/medusa` package. This utility function allows you to extend validators in the core. -2. Import the `AdminPostProductsReq` class from `@medusajs/medusa` as `MedusaAdminPostProductsReq` since this guide extends the Create Product endpoint validator. If you're extending a different validator, make sure to import it instead. +2. Import the `AdminPostProductsReq` class from `@medusajs/medusa` as `MedusaAdminPostProductsReq` since this guide extends the Create Product API Route validator. If you're extending a different validator, make sure to import it instead. 3. Create a class `AdminPostProductsReq` that extends `MedusaAdminPostProductsReq` and adds a new field `custom_field`. Notice that the name of the class must be the same name of the validator defined in the core. `custom_field` has the type `string`. You can change the type or name of the field, or add more fields. 4. Call `registerOverriddenValidators` passing it the `AdminPostProductsReq` class you created. This will override the validator defined in the core to include the new field `custom_field` among the existing fields defined in the core. :::tip -Validators are defined in the same file as the endpoint. To find the validator you need to override, find the endpoint file under `@medusajs/medusa/dist/api/routes` and import the validator in that file. +Validators are defined in the same file as the API Route. To find the validator you need to override, find the API Route file under `@medusajs/medusa/dist/api/routes` and import the validator in that file. ::: @@ -80,4 +79,4 @@ npm run build npx medusa develop ``` -Then, send a request to the endpoint you extended passing it your custom fields. To test out the example in this guide, send an [authenticated request](https://docs.medusajs.com/api/admin#authentication) to the [Create Product endpoint](https://docs.medusajs.com/api/admin#products_postproducts) and pass it the `custom_field` body parameter. The request should execute with no errors. +Then, send a request to the API Route you extended passing it your custom fields. To test out the example in this guide, send an [authenticated request](https://docs.medusajs.com/api/admin#authentication) to the [Create Product API Route](https://docs.medusajs.com/api/admin#products_postproducts) and pass it the `custom_field` body parameter. The request should execute with no errors. diff --git a/www/apps/docs/content/development/api-routes/overview.mdx b/www/apps/docs/content/development/api-routes/overview.mdx new file mode 100644 index 0000000000..f5d2d361da --- /dev/null +++ b/www/apps/docs/content/development/api-routes/overview.mdx @@ -0,0 +1,68 @@ +import DocCardList from '@theme/DocCardList'; +import Icons from '@theme/Icon'; + +# API Routes + +In this document, you’ll learn what API Routes are in Medusa. + +## Introduction + +The Medusa Backend is a Node.js headless server. It exposes commerce functionalities implemented by Medusa's [commerce module](../../modules/overview.mdx) through REST APIs that external or frontend applications can access to process or retrieve data. + +The backend exposes two types of API routes: Store APIs and Admin APIs. The Store APIs are typically accessed from the storefront. For example, you can use the Store APIs to show customers available products or implement a cart and checkout flow. + +The Admin APIs are typically accessed from an admin dashboard. For example, you can use the Admin APIs to allow admins to manage the store’s data such as products, orders, and so on. + + + +--- + +## Custom Development + +Aside from using the Medusa backend's API routes, developers can create their own API routes either directly in the Medusa Backend or in a plugin. + +:::tip + +As the core Medusa package is completely customizable, developers can also extend the functionality even further to implement GraphQL routes. + +::: + + \ No newline at end of file diff --git a/www/apps/docs/content/development/backend/configurations.md b/www/apps/docs/content/development/backend/configurations.md index 5acdfdecf5..e9929f7838 100644 --- a/www/apps/docs/content/development/backend/configurations.md +++ b/www/apps/docs/content/development/backend/configurations.md @@ -52,9 +52,9 @@ This section includes all configurations that belong to the `projectConfig` prop ### admin_cors and store_cors -The Medusa backend’s endpoints are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s endpoints. +The Medusa backend’s API Routes are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s API Routes. -`admin_cors` is used to specify the accepted URLs or patterns for admin endpoints, and `store_cors` is used to specify the accepted URLs or patterns for store endpoints. +`admin_cors` is used to specify the accepted URLs or patterns for admin API Routes, and `store_cors` is used to specify the accepted URLs or patterns for store API Routes. For both the `admin_cors` and `store_cors`, the value is expected to be a string. This string can be a comma-separated list of accepted origins. Every origin in that list can be of the following types: @@ -129,7 +129,7 @@ Its value is an object that has the following properties: - `memLevel`: A `number` value that specifies how much memory should be allocated to the internal compression state. It's an integer in the range of 1 (minimum level) and 9 (maximum level). The default value is `8`. - `threshold`: A `number` or a `string` value in bytes that specifies the minimum response body size that compression is applied on. This is the number of bytes or any string accepted by the bytes module. The default value is `1024`. -If you enable HTTP compression and you want to disable it for specific endpoints, you can pass in the request header `"x-no-compression": true`. +If you enable HTTP compression and you want to disable it for specific API Routes, you can pass in the request header `"x-no-compression": true`. ```js title=medusa-config.js module.exports = { diff --git a/www/apps/docs/content/development/backend/directory-structure.md b/www/apps/docs/content/development/backend/directory-structure.md index 0d39bf18f0..d5339fa3e1 100644 --- a/www/apps/docs/content/development/backend/directory-structure.md +++ b/www/apps/docs/content/development/backend/directory-structure.md @@ -136,9 +136,9 @@ This directory holds all Medusa admin customizations. The main subdirectories of ### api -This directory holds all custom endpoints. You can create as many subdirectories and files that hold endpoint definitions, but only endpoints exported by the `index.ts` file are registered in the Medusa backend. +This directory holds all custom API Routes, which are defined in `route.ts` or `route.js` files. These files can be created in sub-directories of the `api` directory based on the API Route's path. -**Read more:** [Endpoints](../endpoints/overview.mdx) +**Read more:** [API Routes](../api-routes/overview.mdx) ### loaders diff --git a/www/apps/docs/content/development/batch-jobs/create.mdx b/www/apps/docs/content/development/batch-jobs/create.mdx index fd2a263168..1be810de90 100644 --- a/www/apps/docs/content/development/batch-jobs/create.mdx +++ b/www/apps/docs/content/development/batch-jobs/create.mdx @@ -288,7 +288,7 @@ If you follow along with the JS Client code snippets, make sure to [install and ### Create Batch Job -The first step is to create a batch job using the [Create Batch Job endpoint](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created. +The first step is to create a batch job using the [Create Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created. For example, this creates a batch job of the type `publish-products`: diff --git a/www/apps/docs/content/development/batch-jobs/customize-import.md b/www/apps/docs/content/development/batch-jobs/customize-import.md index 98b96ce9aa..9dd7dc3362 100644 --- a/www/apps/docs/content/development/batch-jobs/customize-import.md +++ b/www/apps/docs/content/development/batch-jobs/customize-import.md @@ -103,7 +103,7 @@ npm run build Since you didn’t create a new batch job type and overwrote the functionality of the strategy, you can test out your functionality using the [same steps used with the default strategy](./create.mdx#test-your-batch-job-strategy). -Specifically, since you create batch jobs using the [Create Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) endpoint which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`. +Specifically, since you create batch jobs using the [Create Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`. If you overwrote the import functionality, you can follow [these steps to learn how to import products using the Admin APIs](../../modules/products/admin/import-products.mdx). diff --git a/www/apps/docs/content/development/batch-jobs/index.mdx b/www/apps/docs/content/development/batch-jobs/index.mdx index fee00a8fc3..a8187d9ca1 100644 --- a/www/apps/docs/content/development/batch-jobs/index.mdx +++ b/www/apps/docs/content/development/batch-jobs/index.mdx @@ -49,15 +49,15 @@ When you create a batch job strategy, the `batchType` class property indicates t A batch job’s flow from creation to completion is: -1. A batch job is created using the [Create Batch Job API endpoint](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). +1. A batch job is created using the [Create Batch Job API route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). 2. Once the batch job is created, the batch job’s status is changed to `created` and the `batch.created` event is triggered by the `BatchJobService`. 3. The `BatchJobSubscriber` handles the `created` event. It resolves the batch job strategy based on the `type` of the batch job, then uses it to pre-process the batch job. After this, the batch job’s status is changed to `pre_processed`. Only when the batch job has the status `pre_processed` can be confirmed. -4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobsbatchjobconfirmprocessing) endpoint. +4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobsbatchjobconfirmprocessing). 5. Once the batch job is confirmed, the batch job’s status is changed to `confirmed` and the `batch.confirmed` event is triggered by the `BatchJobService`. 6. The `BatchJobSubscriber` handles the `confirmed` event. It resolves the batch job strategy, then uses it to process the batch job. 7. Once the batch job is processed successfully, the batch job has the status `completed`. -You can track the progress of the batch job at any point using the [Retrieve Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_getbatchjobsbatchjob) endpoint. +You can track the progress of the batch job at any point using the [Retrieve Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_getbatchjobsbatchjob). :::info diff --git a/www/apps/docs/content/development/endpoints/example-logged-in-user.mdx b/www/apps/docs/content/development/endpoints/example-logged-in-user.mdx deleted file mode 100644 index 6e3548a325..0000000000 --- a/www/apps/docs/content/development/endpoints/example-logged-in-user.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -description: 'In this document, you’ll see an example of how you can use middlewares and endpoints to register the logged-in user in the dependency container of your commerce application.' -addHowToData: true ---- - -import Troubleshooting from '@site/src/components/Troubleshooting' -import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md' -import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md' - -# Example: Access Logged-In User - -In this document, you’ll see an example of how you can use middlewares and endpoints to register the logged-in user in the dependency container of your commerce application. You can then access the logged-in user in other resources, such as services. - -This guide showcases how to register the logged-in admin user, but you can apply the same steps if you want to register the current customer. - -This documentation does not explain the basics of [middlewares](./add-middleware.mdx) and [endpoints](./create.mdx). You can refer to their respective guides for more details about each. - -## Step 1: Create the Middleware - -Create the file `src/api/middlewares/logged-in-user.ts` with the following content: - -```ts title=src/api/middlewares/logged-in-user.ts -import { User, UserService } from "@medusajs/medusa" - -export async function registerLoggedInUser(req, res, next) { - let loggedInUser: User | null = null - - if (req.user && req.user.userId) { - const userService = - req.scope.resolve("userService") as UserService - loggedInUser = await userService.retrieve(req.user.userId) - } - - req.scope.register({ - loggedInUser: { - resolve: () => loggedInUser, - }, - }) - - next() -} -``` - -This retrieves the ID of the current user to retrieve an instance of it, then registers it in the scope under the name `loggedInUser`. - ---- - -## Step 2: Apply Middleware on Endpoint - -If you don't have the `cors` package installed, make sure to install it first: - -```bash npm2yarn -npm install cors -``` - -Then, create the file `src/api/routes/create-product.ts` with the following content: - -```ts title=src/api/routes/create-product.ts -import cors from "cors" -import { Router } from "express" -import { - registerLoggedInUser, -} from "../middlewares/logged-in-user" -import - authenticate -from "@medusajs/medusa/dist/api/middlewares/authenticate" - -const router = Router() - -export default function (adminCorsOptions) { - // This router will be applied before the core routes. - // Therefore, the middleware will be executed - // before the create product handler is hit - router.use( - "/admin/products", - cors(adminCorsOptions), - authenticate(), - registerLoggedInUser - ) - return router -} -``` - -In the example above, the middleware is applied on the `/admin/products` core endpoint. However, you can apply it on any other endpoint. You can also apply it to custom endpoints. - -For endpoints that require Cross-Origin Resource Origin (CORS) options, such as core endpoints, you must pass the CORS options to the middleware as well since it will be executed before the underlying endpoint. - -:::tip - -In the above code snippet, the `authenticate` middleware imported from `@medusajs/medusa` is used to ensure that the user is logged in first. If you're implementing this for middleware to register the logged-in customer, make sure to use the [customer's authenticate middleware](./create.mdx#protect-store-routes). - -::: - ---- - -## Step 3: Register Endpoint in the API - -Create the file `src/api/index.ts` with the following content: - -```ts title=src/api/index.ts -import configLoader from "@medusajs/medusa/dist/loaders/config" -import createProductRouter from "./routes/create-product" - -export default function (rootDirectory: string) { - const config = configLoader(rootDirectory) - - const adminCors = { - origin: config.projectConfig.admin_cors.split(","), - credentials: true, - } - - const productRouters = [ - createProductRouter(adminCors), - ] - - return [...productRouters] -} -``` - -This exports an array of endpoints, one of them being the product endpoint that you applied the middleware on in the second step. You can export more endpoints as well. - ---- - -## Step 4: Use in a Service - -You can now access the logged-in user in a service. For example, to access it in a custom service: - - - -```ts -import { Lifetime } from "awilix" -import { - TransactionBaseService, - User, -} from "@medusajs/medusa" - -class HelloService extends TransactionBaseService { - - protected readonly loggedInUser_: User | null - - constructor(container, options) { - super(...arguments) - - try { - this.loggedInUser_ = container.loggedInUser - } catch (e) { - // avoid errors when backend first runs - } - } - - // ... -} - -export default HelloService -``` - -If you're accessing it in an extended core service, it’s important to change the lifetime of the service to `Lifetime.SCOPED`. For example: - - - -```ts -import { Lifetime } from "awilix" -import { - ProductService as MedusaProductService, - User, -} from "@medusajs/medusa" - -// extend core product service -class ProductService extends MedusaProductService { - // The default life time for a core service is SINGLETON - static LIFE_TIME = Lifetime.SCOPED - - protected readonly loggedInUser_: User | null - - constructor(container, options) { - super(...arguments) - - this.loggedInUser_ = container.loggedInUser - } -} - -export default ProductService -``` - -You can learn more about the importance of changing the service lifetime in the [Middlewares documentation](./add-middleware.mdx#note-about-services-lifetime). - ---- - -## Step 5: Test it Out - -To test out your implementation, run the following command in the root directory of the Medusa backend to transpile your changes: - -```bash npm2yarn -npm run build -``` - -Then, run your backend with the following command: - -```bash npm2yarn -npx medusa develop -``` - -If you try accessing the endpoints you added the middleware to, you should see your implementation working as expected. - ---- - -## Troubleshooting - - - }, - { - title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)', - content: - } - ]} -/> diff --git a/www/apps/docs/content/development/endpoints/overview.mdx b/www/apps/docs/content/development/endpoints/overview.mdx deleted file mode 100644 index a1b74b9a8b..0000000000 --- a/www/apps/docs/content/development/endpoints/overview.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -description: "Learn what endpoints are in Medusa. Endpoints are REST APIs that allow a frontend or external system to interact with the Backend." ---- - -import DocCardList from '@theme/DocCardList'; -import Icons from '@theme/Icon'; - -# Endpoints - -In this document, you’ll learn what endpoints are in Medusa. - -## Introduction - -The Medusa Backend is a web server built on top of [Express](https://expressjs.com/), a Node.js web framework. This provides developers with all the functionalities available within Express during development. One of those are endpoints. - -Endpoints are REST APIs that allow a frontend or an external system to interact with the Medusa Backend to retrieve and process data, or perform business logic. Endpoints are [Express routes](https://expressjs.com/en/starter/basic-routing.html). - -Each [commerce module](../../modules/overview.mdx) contains a set of endpoints specific to the functionalities that it provides. Since the core package that powers the Medusa Backend acts as an orchestrator of commerce modules and exposes their endpoints, the endpoints of each of these commerce modules are available within the Medusa Backend. - -The commerce modules provide two types of endpoints: Store APIs and Admin APIs. The Store APIs are typically accessed from the storefront. For example, you can use the Store APIs to show customers available products or implement a cart and checkout flow. - -The Admin APIs are typically accessed from an admin dashboard. For example, you can use the Admin APIs to allow admins to manage the store’s data such as products, orders, and so on. - - - ---- - -## Custom Development - -Aside from using the endpoints that commerce modules, developers can create their own REST APIs either directly in the Medusa Backend, in a plugin, or in a custom commerce module. - -:::tip - -As the core Medusa package is completely customizable, developers can also extend the functionality even further to implement GraphQL endpoints. - -::: - - \ No newline at end of file diff --git a/www/apps/docs/content/development/entities/extend-entity.md b/www/apps/docs/content/development/entities/extend-entity.md index 8d41551ac7..24a8310654 100644 --- a/www/apps/docs/content/development/entities/extend-entity.md +++ b/www/apps/docs/content/development/entities/extend-entity.md @@ -124,21 +124,21 @@ You can now use your extended entity throughout your commerce application. --- -## Access Custom Attributes and Relations in Core Endpoints +## Access Custom Attributes and Relations in Core API Routes ### Request Parameters -In most cases, after you extend an entity to add new attributes, you'll likely need to pass these attributes to endpoints defined in the core. By default, this causes an error, as request parameters are validated to ensure only those that are defined are passed to the endpoint. +In most cases, after you extend an entity to add new attributes, you'll likely need to pass these attributes to API Routes defined in the core. By default, this causes an error, as request parameters are validated to ensure only those that are defined are passed to the API Route. -To allow passing your custom attribute, you'll need to [extend the validator](../endpoints/extend-validator.md) of the endpoint. +To allow passing your custom attribute, you'll need to [extend the validator](../api-routes/extend-validator.md) of the API Route. ### Response Fields -After you add custom attributes, you'll notice that these attributes aren't returned as part of the response fields of core endpoints. Core endpoints have a defined set of fields and relations that can be returned by default in requests. +After you add custom attributes, you'll notice that these attributes aren't returned as part of the response fields of core API Routes. Core API Routes have a defined set of fields and relations that can be returned by default in requests. -To change that and ensure your custom attribute is returned in your request, you can extend the allowed fields of a set of endpoints in a loader file and add your attribute into them. +To change that and ensure your custom attribute is returned in your request, you can extend the allowed fields of a set of API Routes in a loader file and add your attribute into them. -For example, if you added a custom attribute in the `Product` entity and you want to ensure it's returned in all the product's store endpoints (endpoints under the prefix `/store/products`), you can create a file under the `src/loaders` directory in your Medusa backend with the following content: +For example, if you added a custom attribute in the `Product` entity and you want to ensure it's returned in all the product's store API Routes (API Routes under the prefix `/store/products`), you can create a file under the `src/loaders` directory in your Medusa backend with the following content: ```ts title=src/loaders/extend-product-fields.ts export default async function () { @@ -156,10 +156,10 @@ export default async function () { } ``` -In the code snippet above, you import `@medusajs/medusa/dist/api/routes/store/products/index`, which is where all the product's store endpoints are exported. In that file, there are the following defined variables: +In the code snippet above, you import `@medusajs/medusa/dist/api/routes/store/products/index`, which is where all the product's store API Routes are exported. In that file, there are the following defined variables: -- `allowedStoreProductsFields`: The fields or attributes of a product that are allowed to be retrieved and returned in the product's store endpoints. This would allow you to pass your custom attribute in the `fields` request parameter of the product's store endpoints. -- `defaultStoreProductsFields`: The fields or attributes of a product that are retrieved and returned by default in the product's store endpoints. +- `allowedStoreProductsFields`: The fields or attributes of a product that are allowed to be retrieved and returned in the product's store API Routes. This would allow you to pass your custom attribute in the `fields` request parameter of the product's store API Routes. +- `defaultStoreProductsFields`: The fields or attributes of a product that are retrieved and returned by default in the product's store API Routes. You change the values of these variables and pass the name of your custom attribute. Make sure to change `customAttribute` to the name of your custom attribute. @@ -171,10 +171,10 @@ Before you test out the above change, make sure to build your changes before you You can also add custom relations by changing the following defined variables: -- `allowedStoreProductsRelations`: The relations of a product that are allowed to be retrieved and returned in the product's store endpoints. This would allow you to pass your custom relation in the `expand` request parameter of the product's store endpoints. -- `defaultStoreProductsRelations`: The relations of a product that are retrieved and returned by default in the product's store endpoints. +- `allowedStoreProductsRelations`: The relations of a product that are allowed to be retrieved and returned in the product's store API Routes. This would allow you to pass your custom relation in the `expand` request parameter of the product's store API Routes. +- `defaultStoreProductsRelations`: The relations of a product that are retrieved and returned by default in the product's store API Routes. -If you want to apply this example for a different entity or set of endpoints, you would need to change the import path `@medusajs/medusa/dist/api/routes/store/products/index` to the path of the endpoints you're targeting. You also need to change `allowedStoreProductsFields` and `defaultStoreProductsFields` to the names of the variables in that file, and the same goes for relations. Typically, these names would be of the format `(allowed|default)(Store|Admin)(Entity)(Fields|Relation)`. +If you want to apply this example for a different entity or set of API Routes, you would need to change the import path `@medusajs/medusa/dist/api/routes/store/products/index` to the path of the API Routes you're targeting. You also need to change `allowedStoreProductsFields` and `defaultStoreProductsFields` to the names of the variables in that file, and the same goes for relations. Typically, these names would be of the format `(allowed|default)(Store|Admin)(Entity)(Fields|Relation)`. --- diff --git a/www/apps/docs/content/development/entities/extend-repository.md b/www/apps/docs/content/development/entities/extend-repository.md index 237324cc7c..853295904f 100644 --- a/www/apps/docs/content/development/entities/extend-repository.md +++ b/www/apps/docs/content/development/entities/extend-repository.md @@ -83,32 +83,35 @@ After that, you can add your custom methods to the repository. In the example ab ## Step 3: Use Your Extended Repository -You can now use your extended repository in other resources such as services or endpoints. +You can now use your extended repository in other resources such as services or API Routes. -Here’s an example of using it in an endpoint: +Here’s an example of using it in an API Route: -```ts +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import ProductRepository from "./path/to/product.ts" -import EntityManager from "@medusajs/medusa" +import { EntityManager } from "typeorm" -export default () => { +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // ... - router.get("/custom-endpoint", (req, res) => { - // ... + const productRepository: typeof ProductRepository = + req.scope.resolve( + "productRepository" + ) + const manager: EntityManager = req.scope.resolve("manager") + const productRepo = manager.withRepository( + productRepository + ) + productRepo.customFunction() - const productRepository: typeof ProductRepository = - req.scope.resolve( - "productRepository" - ) - const manager: EntityManager = req.scope.resolve("manager") - const productRepo = manager.withRepository( - productRepository - ) - productRepo.customFunction() - - // ... - }) + // ... } ``` diff --git a/www/apps/docs/content/development/entities/migrations/overview.mdx b/www/apps/docs/content/development/entities/migrations/overview.mdx index c60fceb6bb..9cf6d8e508 100644 --- a/www/apps/docs/content/development/entities/migrations/overview.mdx +++ b/www/apps/docs/content/development/entities/migrations/overview.mdx @@ -80,10 +80,10 @@ Developers can create custom entities in the Medusa backend, a plugin, or in a m { type: 'link', href: '/development/entities/create', - label: 'Create an Endpoint', + label: 'Create an API Route', customProps: { icon: Icons['academic-cap-solid'], - description: 'Learn how to create endpoints in Medusa.' + description: 'Learn how to create API Routes in Medusa.' } }, ]} /> \ No newline at end of file diff --git a/www/apps/docs/content/development/entities/repositories.md b/www/apps/docs/content/development/entities/repositories.md index 47bb31087f..51562de383 100644 --- a/www/apps/docs/content/development/entities/repositories.md +++ b/www/apps/docs/content/development/entities/repositories.md @@ -39,27 +39,26 @@ class PostService extends TransactionBaseService { } ``` -Another example is retrieving the default repository of an entity in an endpoint: +Another example is retrieving the default repository of an entity in an API Route: -```ts title=src/api/index.ts +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import { Post } from "../models/post" import { EntityManager } from "typeorm" -// ... +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const manager: EntityManager = req.scope.resolve("manager") + const postRepo = manager.getRepository(Post) -export default () => { - // ... - - storeRouter.get("/posts", async (req, res) => { - const manager: EntityManager = req.scope.resolve("manager") - const postRepo = manager.getRepository(Post) - - return res.json({ - posts: await postRepo.find(), - }) + return res.json({ + posts: await postRepo.find(), }) - - // ... } ``` @@ -105,35 +104,36 @@ A data source is Typeorm’s connection settings that allows you to connect to y ## Using Custom Repositories in Other Resources -### Endpoints +### API Routes -To access a custom repository within an endpoint, use the `req.scope.resolve` method. For example: +To access a custom repository within an API Route, use the `MedusaRequest` object's `scope.resolve` method. -```ts title=src/api/index.ts +For example: + +```ts title=src/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import { PostRepository } from "../repositories/post" import { EntityManager } from "typeorm" -// ... +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const postRepository: typeof PostRepository = + req.scope.resolve("postRepository") + const manager: EntityManager = req.scope.resolve("manager") + const postRepo = manager.withRepository(postRepository) -export default () => { - // ... - - storeRouter.get("/posts", async (req, res) => { - const postRepository: typeof PostRepository = - req.scope.resolve("postRepository") - const manager: EntityManager = req.scope.resolve("manager") - const postRepo = manager.withRepository(postRepository) - - return res.json({ - posts: await postRepo.find(), - }) + return res.json({ + posts: await postRepo.find(), }) - - // ... } ``` -You can learn more about endpoints [here](../endpoints/overview.mdx). +You can learn more about API Route [here](../api-routes/overview.mdx). ### Services and Subscribers @@ -336,4 +336,4 @@ You can later retrieve that entity by passing the `withDeleted` option to method const posts = await postRepository.find({ withDeleted: true, }) -``` \ No newline at end of file +``` diff --git a/www/apps/docs/content/development/events/events-list.md b/www/apps/docs/content/development/events/events-list.md index 1554c7296c..0f3bb93e8e 100644 --- a/www/apps/docs/content/development/events/events-list.md +++ b/www/apps/docs/content/development/events/events-list.md @@ -2218,7 +2218,7 @@ Triggered when a product and data associated with it (options, variant orders, e The entire product passed as an object. You can refer to the [Product entity](../../references/entities/classes/Product.md) for an idea of what fields to expect. -In one case, when the `/admin/products/{id}` endpoint is used to update the product, the payload is an object of the following format: +In one case, when the `/admin/products/{id}` API Route is used to update the product, the payload is an object of the following format: ```js noReport noCopy { diff --git a/www/apps/docs/content/development/feature-flags/overview.mdx b/www/apps/docs/content/development/feature-flags/overview.mdx index 71fb95b31a..5db374c975 100644 --- a/www/apps/docs/content/development/feature-flags/overview.mdx +++ b/www/apps/docs/content/development/feature-flags/overview.mdx @@ -13,7 +13,7 @@ In this document, you’ll learn what feature flags in Medusa. Feature flags are used in Medusa to guard beta features that aren’t ready for live and production applications. This allows the Medusa team to keep publishing releases more frequently, while also working on necessary future features behind the scenes. To use these beta features, you must enable their feature flags. -If a feature is guarded by a flag, entities, migrations, endpoints, and other resources associated with that feature are guarded by that flag as well. So, these resources will only be available to use in Medusa if you have enabled the associated feature flag. +If a feature is guarded by a flag, entities, migrations, API Routes, and other resources associated with that feature are guarded by that flag as well. So, these resources will only be available to use in Medusa if you have enabled the associated feature flag. You can view a list of available feature flags that you can toggle in [the Beta Features documentation](../../beta.md). diff --git a/www/apps/docs/content/development/feature-flags/toggle.md b/www/apps/docs/content/development/feature-flags/toggle.md index 15771594ce..842f123004 100644 --- a/www/apps/docs/content/development/feature-flags/toggle.md +++ b/www/apps/docs/content/development/feature-flags/toggle.md @@ -74,7 +74,7 @@ You can learn more about migrations in this documentation. Disabling feature flags follows the same process as enabling the feature flags. All you have to do is change the value in the environment variables or the backend configurations to `false`. -Once you disable a feature flag, all endpoints, entities, services, or other related classes and functionalities are disabled. +Once you disable a feature flag, all API Routes, entities, services, or other related classes and functionalities are disabled. ### Revert Migrations diff --git a/www/apps/docs/content/development/file-service/create-file-service.md b/www/apps/docs/content/development/file-service/create-file-service.md index 0145fea73e..cb07116f95 100644 --- a/www/apps/docs/content/development/file-service/create-file-service.md +++ b/www/apps/docs/content/development/file-service/create-file-service.md @@ -438,7 +438,7 @@ Run your backend to test it out: npx medusa develop ``` -Then, try uploading a file, for example, using the [Upload File endpoint](https://docs.medusajs.com/api/admin#uploads_postuploads). The file should be uploaded based on the logic you’ve implemented. +Then, try uploading a file, for example, using the [Upload File API Route](https://docs.medusajs.com/api/admin#uploads_postuploads). The file should be uploaded based on the logic you’ve implemented. ### (Optional) Accessing the File @@ -452,15 +452,17 @@ Since the file is uploaded to a local directory `uploads`, you need to configure To do that, create the file `src/api/index.ts` with the following content: -```ts +```ts title=src/api/middlewares.ts +import type { MiddlewaresConfig } from "@medusajs/medusa" import express from "express" -export default () => { - const app = express.Router() - - app.use(`/uploads`, express.static(uploadDir)) - - return app +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/uploads", + middlewares: [express.static(uploadDir)], + }, + ], } ``` diff --git a/www/apps/docs/content/development/fundamentals/architecture-overview.md b/www/apps/docs/content/development/fundamentals/architecture-overview.md index b282cb9260..90a74a85d6 100644 --- a/www/apps/docs/content/development/fundamentals/architecture-overview.md +++ b/www/apps/docs/content/development/fundamentals/architecture-overview.md @@ -8,20 +8,20 @@ In this document, you'll get an overview of Medusa's architecture to better unde ## Architecture Overview -Medusa's core package `@medusajs/medusa` is a Node.js backend built on top of [Express](https://expressjs.com/). It combines all the [Commerce Modules](../../modules/overview.mdx) that Medusa provides. Commerce Modules are ecommerce features that can be used as building blocks in an ecommerce ecosystem. Product is an example of a Commerce Module. +Medusa's core package `@medusajs/medusa` is a Node.js headless server. It combines all the [Commerce Modules](../../modules/overview.mdx) that Medusa provides. Commerce Modules are ecommerce features that can be used as building blocks in an ecommerce ecosystem. Product is an example of a Commerce Module. -![Medusa Core Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1677607702/Medusa%20Docs/Diagrams/medusa-architecture-3_e385zk.jpg) +![Medusa Core Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1697706240/Medusa%20Docs/Diagrams/medusa_architecture_qvg9a3.jpg) The backend connects to a database, such as [PostgreSQL](https://www.postgresql.org/), to store the ecommerce store’s data. The tables in that database are represented by [Entities](../entities/overview.mdx), built on top of [Typeorm](https://typeorm.io/). Entities can also be reflected in the database using [Migrations](../entities/migrations/overview.mdx). The retrieval, manipulation, and other utility methods related to that entity are created inside a [Service](../services/overview.mdx). Services are TypeScript or JavaScript classes that, along with other resources, can be accessed throughout the Medusa backend through [dependency injection](./dependency-injection.md). -The backend does not have any tightly-coupled frontend. Instead, it exposes [Endpoints](../endpoints/overview.mdx) which are REST APIs that frontends such as an admin or a storefront can use to communicate with the backend. Endpoints are [Express routes](https://expressjs.com/en/guide/routing.html). +The backend doesn't have any tightly-coupled frontend. Instead, it exposes [API Routes](../api-routes/overview.mdx) which are REST APIs that frontends such as an admin or a storefront can use to communicate with the backend. Medusa also uses an [Events Architecture](../events/index.mdx) to trigger and handle events. Events are triggered when a specific action occurs, such as when an order is placed. To manage this events system, Medusa connects to a service that implements a pub/sub model, such as [Redis](https://redis.io/). Events can be handled using [Subscribers](../events/subscribers.mdx). Subscribers are TypeScript or JavaScript classes that add their methods as handlers for specific events. These handler methods are only executed when an event is triggered. -You can create any of the resources in the backend’s architecture, such as entities, endpoints, services, and more, as part of your custom development without directly modifying the backend itself. The Medusa backend uses [loaders](../loaders/overview.mdx) to load the backend’s resources, as well as your custom resources and resources in [Plugins](../plugins/overview.mdx). +You can create any of the resources in the backend’s architecture, such as entities, API Routes, services, and more, as part of your custom development without directly modifying the backend itself. The Medusa backend uses [loaders](../loaders/overview.mdx) to load the backend’s resources, as well as your custom resources and resources in [Plugins](../plugins/overview.mdx). You can package your customizations into Plugins to reuse them in different Medusa backends or publish them for others to use. You can also install existing plugins into your Medusa backend. diff --git a/www/apps/docs/content/development/fundamentals/dependency-injection.md b/www/apps/docs/content/development/fundamentals/dependency-injection.md index 04e40e609b..0390aa5b0d 100644 --- a/www/apps/docs/content/development/fundamentals/dependency-injection.md +++ b/www/apps/docs/content/development/fundamentals/dependency-injection.md @@ -16,7 +16,7 @@ Generally, all resources are registered in a container. Then, whenever a class d ### Medusa’s Dependency Container -Medusa uses a dependency container to register essential resources of the backend. You can then access these resources in classes and endpoints using the dependency container. +Medusa uses a dependency container to register essential resources of the backend. You can then access these resources in classes and API Routes using the dependency container. For example, if you create a custom service, you can access any other service registered in Medusa in your service’s constructor. That includes Medusa’s core services, services defined in plugins, or other services that you create on your backend. @@ -28,7 +28,7 @@ To manage dependency injections, Medusa uses [Awilix](https://github.com/jeffijo When you run the Medusa backend, a container of the type `MedusaContainer` is created. This type extends the [AwilixContainer](https://github.com/jeffijoe/awilix#the-awilixcontainer-object) object. -The backend then registers all important resources in the container, which makes them accessible in classes and endpoints. +The backend then registers all important resources in the container, which makes them accessible in classes and API Routes. --- @@ -695,11 +695,11 @@ Its camel-case name. ## Resolve Resources -This section covers how to resolve resources from the dependency container to use them in endpoints and classes in general. +This section covers how to resolve resources from the dependency container to use them in API Routes and classes in general. -### In Endpoints +### In API Routes -To resolve resources, such as services, in endpoints, use the `req.scope.resolve` method. The method receives the registration name of the resource as a parameter. +To resolve resources, such as services, in API Routes, use the `MedusaRequest` object's `scope.resolve` method. The method receives the registration name of the resource as a parameter. For example: @@ -707,7 +707,7 @@ For example: const logger = req.scope.resolve("logger") ``` -Please note that in endpoints some resources, such as repositories, are not available. Refer to the [repositories](../entities/repositories.md) documentation to learn how you can load them. +Please note that in API Routes some resources, such as repositories, aren't available. Refer to the [repositories](../entities/repositories.md#api-routes) documentation to learn how you can load them. ### In Classes diff --git a/www/apps/docs/content/development/fundamentals/local-development.md b/www/apps/docs/content/development/fundamentals/local-development.md index 1259d1f43d..64c57e1c7c 100644 --- a/www/apps/docs/content/development/fundamentals/local-development.md +++ b/www/apps/docs/content/development/fundamentals/local-development.md @@ -104,7 +104,7 @@ yarn test ### Run API Integration Tests -API integration tests are used to test out Medusa’s core endpoints. +API integration tests are used to test out Medusa’s core API Routes. To run the API integration tests, run the following command in the root directory of the repository: diff --git a/www/apps/docs/content/development/idempotency-key/overview.mdx b/www/apps/docs/content/development/idempotency-key/overview.mdx index e8ab25490f..dd8d565241 100644 --- a/www/apps/docs/content/development/idempotency-key/overview.mdx +++ b/www/apps/docs/content/development/idempotency-key/overview.mdx @@ -11,7 +11,7 @@ In this document, you'll learn what an idempotency key is in Medusa. ## Overview -An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an endpoint. This allows you to safely retry requests without accidentally performing the same operation twice. +An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an API Route. This allows you to safely retry requests without accidentally performing the same operation twice. For example, if a connection error occurs while the customer is completing their cart and placing an order, you can retry from the last recovery point before the error occurred. diff --git a/www/apps/docs/content/development/idempotency-key/use-service.md b/www/apps/docs/content/development/idempotency-key/use-service.md index 8b8c401a4e..ca0831dcdf 100644 --- a/www/apps/docs/content/development/idempotency-key/use-service.md +++ b/www/apps/docs/content/development/idempotency-key/use-service.md @@ -9,7 +9,7 @@ In this document, you'll learn how to use the `IdempotencyKeyService`. ## Overview -You can use the `IdempotencyKeyService` within your custom development to ensure that your custom endpoints and operations can be safely retried or continued if an error occurs. This guide is also useful if you're overriding an existing feature in Medusa that uses the `IdempotencyKeyService` and you want to maintain its usage, such as if you're overriding the cart completion strategy. +You can use the `IdempotencyKeyService` within your custom development to ensure that your custom API Routes and operations can be safely retried or continued if an error occurs. This guide is also useful if you're overriding an existing feature in Medusa that uses the `IdempotencyKeyService` and you want to maintain its usage, such as if you're overriding the cart completion strategy. The `IdempotencyKeyService` includes methods that can be used to create and update idempotency keys, among other functionalities. @@ -17,18 +17,30 @@ The `IdempotencyKeyService` includes methods that can be used to create and upda ## Create Idempotency Key -You can create an idempotency key within an endpoint using the `create` method of the `IdempotencyKeyService`: +You can create an idempotency key within an API Route using the `create` method of the `IdempotencyKeyService`: -```ts -router.post("/custom-route", async (req, res) => { +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { IdempotencyKeyService } from "@medusajs/medusa" + +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // ... + const idempotencyKeyService = req.scope.resolve< + IdempotencyKeyService + >("idempotencyKeyService") const idempotencyKey = await idempotencyKeyService.create({ request_method: req.method, request_params: req.params, request_path: req.path, }) // ... -}) +} ``` The method requires as a parameter an object having the following properties: @@ -41,9 +53,23 @@ The method handles generating the idempotency key value and saving the idempoten Alternatively, you can use the `initializeRequest` method that allows you to retrieve an idempotency key based on the value passed in the `Idempotency-Key` header of the request if it exists, or create a new key otherwise. For example: -```ts -router.post("/custom-route", async (req, res) => { +```ts title=src/api/store/custom/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +import { + IdempotencyKeyService, +} from "@medusajs/medusa" + +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // ... + const idempotencyKeyService = req.scope.resolve< + IdempotencyKeyService + >("idempotencyKeyService") const headerKey = req.get("Idempotency-Key") || "" const idempotencyKey = await idempotencyKeyService @@ -54,7 +80,7 @@ router.post("/custom-route", async (req, res) => { req.path ) // ... -}) +} ``` The method requires the following parameters: diff --git a/www/apps/docs/content/development/notification/create-notification-provider.md b/www/apps/docs/content/development/notification/create-notification-provider.md index e4dcec4fee..af28b6d2fc 100644 --- a/www/apps/docs/content/development/notification/create-notification-provider.md +++ b/www/apps/docs/content/development/notification/create-notification-provider.md @@ -200,12 +200,12 @@ The `to` and `data` properties are used in the `NotificationService` in Medusa ### resendNotification -Using the [Resend Notification endpoint](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusa’s core then executes the `resendNotification` method in your Notification Provider. +Using the [Resend Notification API Route](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusa’s core then executes the `resendNotification` method in your Notification Provider. This method receives three parameters: 1. `notification`: This is the original Notification record that was created after you sent the notification with `sendNotification`. You can get an overview of the entity and its attributes in the [architecture overview](./overview.mdx#notification-entity-overview), but most notably it includes the `to` and `data` attributes which are populated originally using the `to` and `data` properties of the object you return in `sendNotification`. -2. `config`: In the Resend Notification endpoint you may specify an alternative receiver of the notification using the `to` request body parameter. For example, you may want to resend the order confirmation email to a different email. If that’s the case, you have access to it in the `config` parameter object. Otherwise, `config` will be an empty object. +2. `config`: In the Resend Notification API Route you may specify an alternative receiver of the notification using the `to` request body parameter. For example, you may want to resend the order confirmation email to a different email. If that’s the case, you have access to it in the `config` parameter object. Otherwise, `config` will be an empty object. 3. `attachmentGenerator`: If you’ve previously attached a generator to the Notification Service using the [`registerAttachmentGenerator`](../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null. Similarly to the `sendNotification` method, this method must return an object containing two properties: @@ -323,21 +323,21 @@ After placing an order, you can see in your console the message “Notification ## Test Resending Notifications with your Notification Provider -To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications admin endpoint](https://docs.medusajs.com/api/admin#notifications_getnotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent. +To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications API Route](https://docs.medusajs.com/api/admin#notifications_getnotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent. :::tip -You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User](https://docs.medusajs.com/api/admin#auth_postauth) endpoint to get authenticated. +You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User API Route](https://docs.medusajs.com/api/admin#auth_postauth) to get authenticated. ::: ![List Notifications Request](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001650/Medusa%20Docs/Screenshots/iF1rZX1_msps2t.png) -Then, send a request to the [Resend Notification](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend) endpoint using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent. +Then, send a request to the [Resend Notification API Route](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend) using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent. ![Resend Notifications Request](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001659/Medusa%20Docs/Screenshots/0zFfPed_og7one.png) -This request returns the same notification object as the List Notifications endpoint, but it now has a new object in the `resends` array. This is the resent notification. If you supplied a `to` parameter in the request body, you should see its value in the `to` property of the resent notification object. +This request returns the same notification object as the List Notifications API Route, but it now has a new object in the `resends` array. This is the resent notification. If you supplied a `to` parameter in the request body, you should see its value in the `to` property of the resent notification object. --- diff --git a/www/apps/docs/content/development/notification/overview.mdx b/www/apps/docs/content/development/notification/overview.mdx index b138fe36cb..54938fc204 100644 --- a/www/apps/docs/content/development/notification/overview.mdx +++ b/www/apps/docs/content/development/notification/overview.mdx @@ -86,7 +86,7 @@ With Medusa you can create notifications as a reaction to a wide spectrum of eve An example of a flow that can be implemented using Medusa's Notification API is automated return flows: -- A customer requests a return by sending a `POST` request to the `/store/returns` endpoint. +- A customer requests a return by sending a `POST` request to the `/store/returns` API Route. - The Notification Provider listens to the `order.return_requested` event and sends an email to the customer with a return invoice and return label generated by the Fulfillment Provider. - The customer returns the items triggering the `return.received` event. - The Notification Provider listens to the `return.received` event and sends an email to the customer with confirmation that their items have been received and that a refund has been issued. diff --git a/www/apps/docs/content/development/overview.mdx b/www/apps/docs/content/development/overview.mdx index 6c71937026..b76c357a38 100644 --- a/www/apps/docs/content/development/overview.mdx +++ b/www/apps/docs/content/development/overview.mdx @@ -36,7 +36,14 @@ When you build a commerce application with Medusa, you’ll typically interact w For example, imagine an Inventory module that contains lightweight logic to increment and decrement stock levels for a Stock-Keeping Unit (SKU). In a commerce application, you typically want to associate the stock levels with a specific product. Medusa offers both an Inventory module and a Product module, and the core package creates associations between these modules and executing the related business logic. So, the core package contains code similar to this: ```ts -async function handler(req, res) { +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // ... // associate a product with an inventory item @@ -57,7 +64,7 @@ async function handler(req, res) { The goal of orchestrating the modules is to expose an API that client applications, like websites or apps, can consume. By default, Medusa’s core package exposes a REST API that offers commerce functionalities similar to what other platforms give you. -The core package also holds the logic that allows developers to extend and add custom endpoints, among other available customizations. +The core package also holds the logic that allows developers to extend and add custom API Routes, among other available customizations. --- @@ -111,8 +118,8 @@ These concepts will guide you through your development and building customizatio }, { type: 'link', - href: '/development/endpoints/overview', - label: 'Endpoints', + href: '/development/api-routes/overview', + label: 'API Routes', customProps: { icon: Icons['academic-cap-solid'], description: 'REST APIs that frontends consume to communicate with the backend.' @@ -194,9 +201,9 @@ By installing a Module in your project and expose its APIs based on the framewor Developers can use Medusa’s toolkit to create their ecommerce system. With the use of the [create-medusa-app](../create-medusa-app.mdx) command, developers can set up a Medusa Backend, Medusa admin, and a storefront. -![Full-Fledged Ecommerce System](https://res.cloudinary.com/dza7lstvk/image/upload/v1678954316/Medusa%20Docs/Diagrams/fully-fledged-ecom_qqwraq.jpg) +![Full-Fledged Ecommerce System](https://res.cloudinary.com/dza7lstvk/image/upload/v1697707368/Medusa%20Docs/Diagrams/Social_Media_Graphics_vosikk.jpg) -Developers can still benefit from customization opportunities here that Medusa provides. This includes creating resources such as endpoints and services, creating plugins, integrating third-party services, create a custom storefront, and more. +Developers can still benefit from customization opportunities here that Medusa provides. This includes creating resources such as API Routes and services, creating plugins, integrating third-party services, create a custom storefront, and more. ### Your Own Use Case diff --git a/www/apps/docs/content/development/plugins/create.mdx b/www/apps/docs/content/development/plugins/create.mdx index 22eea02a17..bd4a7fa402 100644 --- a/www/apps/docs/content/development/plugins/create.mdx +++ b/www/apps/docs/content/development/plugins/create.mdx @@ -196,17 +196,11 @@ Make sure to delete these files if you're not using them in your plugin. ### Plugin Structure -While developing your plugin, you can create your TypeScript or JavaScript files under the `src` directory. This includes creating services, endpoints, migrations, and other resources. +While developing your plugin, you can create your TypeScript or JavaScript files under the `src` directory. This includes creating services, API Routes, migrations, and other resources. However, before you test the changes on a Medusa backend or publish your plugin, you must transpile your files and move them either to a `dist` directory or to the root of the plugin's directory. -For example, if you have an endpoint in `src/api/index.js`, after running the `build` or `watch` commands [as defined earlier](#recommended-change-scripts), the file should be transpiled into `dist/api/index.js` in your plugin's root. You can alternative transpile them into the `api/index.js` in your plugin's root. - -:::note - -It was previously required to output your files into the root of the plugin's directory (for example, `api/index.js` instead of `dist/api/index.js`). As of v1.8, you can either have your files in the root of the directory or under the `dist` directory. - -::: +For example, if you have an API Route in `src/api/store/custom/route.ts`, after running the `build` or `watch` commands [as defined earlier](#recommended-change-scripts), the file should be transpiled into `dist/api/store/custom/route.ts` in your plugin's root. You can alternative transpile them into the `api/store/custom/route.ts` in your plugin's root. ### Development Resources @@ -233,11 +227,11 @@ This guide doesn't cover how to create different files and components. If you’ }, { type: 'link', - href: '/development/endpoints/create', - label: 'Create an Endpoint', + href: '/development/api-routes/create', + label: 'Create an API Route', customProps: { icon: Icons['academic-cap-solid'], - description: 'Learn how to create an endpoint.' + description: 'Learn how to create an API Route.' } }, { @@ -364,27 +358,6 @@ class MyService extends TransactionBaseService { } ``` -You can also access the options in your plugin's endpoints. The second parameter that the function declared in `src/api/index.ts` receives is an object including your plugin's configurations. - -For example: - -```js title=src/api/index.ts -// in an endpoint in your plugin -export default (rootDirectory, options) => { - // options contain the plugin options - const router = Router() - - router.get("/hello-world", (req, res) => { - res.json({ - message: - `Welcome to ${options.name ? options.name : "Medusa"}!`, - }) - }) - - return router -} -``` - :::tip Make sure to include in the README of your plugin the options that can be passed to a plugin. diff --git a/www/apps/docs/content/development/publishable-api-keys/admin/manage-publishable-api-keys.mdx b/www/apps/docs/content/development/publishable-api-keys/admin/manage-publishable-api-keys.mdx index 85e8ca9af1..8b84b058d2 100644 --- a/www/apps/docs/content/development/publishable-api-keys/admin/manage-publishable-api-keys.mdx +++ b/www/apps/docs/content/development/publishable-api-keys/admin/manage-publishable-api-keys.mdx @@ -61,7 +61,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Publishable API Keys -You can retrieve a list of publishable API keys by sending a request to the [List Publishable API Keys](https://docs.medusajs.com/api/admin#publishable-api-keys_getpublishableapikeys) endpoint: +You can retrieve a list of publishable API keys by sending a request to the [List Publishable API Keys route](https://docs.medusajs.com/api/admin#publishable-api-keys_getpublishableapikeys): @@ -152,7 +152,7 @@ You can learn more about pagination in the [API reference](https://docs.medusajs ## Create a Publishable API Key -You can create a publishable API key by sending a request to the [Create Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeys) endpoint: +You can create a publishable API key by sending a request to the [Create Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeys): @@ -231,7 +231,7 @@ It returns the created publishable API key in the response. ## Update a Publishable API Key -You can update a publishable API key’s details by sending a request to the [Update Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikyspublishableapikey) endpoint: +You can update a publishable API key’s details by sending a request to the [Update Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikyspublishableapikey): @@ -316,7 +316,7 @@ This request returns the update publishable API key object in the response. Revoking a publishable API key does not remove it, but does not allow using it in future requests. -You can revoke a publishable API key by sending a request to the [Revoke Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeyspublishableapikeyrevoke) endpoint: +You can revoke a publishable API key by sending a request to the [Revoke Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeyspublishableapikeyrevoke): @@ -386,7 +386,7 @@ This request requires the ID of the publishable API key as a path parameter. It ## Delete a Publishable API Key -You can delete a publishable API key by sending a request to the [Delete Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeyspublishableapikey) endpoint: +You can delete a publishable API key by sending a request to the [Delete Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeyspublishableapikey): @@ -463,7 +463,7 @@ This section covers how to manage sales channels in a publishable API key. This ### List Sales Channels of a Publishable API Key -You can retrieve the list of sales channels associated with a publishable API key by sending a request to the [List Sales Channels](https://docs.medusajs.com/api/admin#sales-channels_getsaleschannels) endpoint: +You can retrieve the list of sales channels associated with a publishable API key by sending a request to the [List Sales Channels API Route](https://docs.medusajs.com/api/admin#sales-channels_getsaleschannels): @@ -546,7 +546,7 @@ It returns an array of sales channels associated with the publishable API key in ### Add Sales Channels to Publishable API Key -You can add a sales channel to a publishable API key by sending a request to the [Add Sales Channels](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeysaleschannelschannelsbatch) endpoint: +You can add a sales channel to a publishable API key by sending a request to the [Add Sales Channels API Route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeysaleschannelschannelsbatch): @@ -656,7 +656,7 @@ This request returns the updated publishable API key in the response. ### Delete Sales Channels from a Publishable API Key -You can delete a sales channel from a publishable API key by sending a request to the [Delete Sales Channels](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeysaleschannelschannelsbatch) endpoint: +You can delete a sales channel from a publishable API key by sending a request to the [Delete Sales Channels API Route](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeysaleschannelschannelsbatch): diff --git a/www/apps/docs/content/development/publishable-api-keys/index.mdx b/www/apps/docs/content/development/publishable-api-keys/index.mdx index d123f3bcfd..2de4c78a70 100644 --- a/www/apps/docs/content/development/publishable-api-keys/index.mdx +++ b/www/apps/docs/content/development/publishable-api-keys/index.mdx @@ -13,7 +13,7 @@ In this document, you’ll learn about Publishable API Keys and their architectu While using Medusa’s APIs, you might have to pass some query parameters for certain resources with every or most requests. -Taking Sales Channels as an example, you have to pass the Sales Channel’s ID as a query parameter to all the necessary endpoints, such as the List Products endpoint. +Taking Sales Channels as an example, you have to pass the Sales Channel’s ID as a query parameter to all the necessary API Routes, such as the List Products API Route. This is a tedious and error-prone process. This is where Publishable API Keys are useful. diff --git a/www/apps/docs/content/development/publishable-api-keys/storefront/use-in-requests.md b/www/apps/docs/content/development/publishable-api-keys/storefront/use-in-requests.md index 3c74cf3faa..7c3fbcf0bd 100644 --- a/www/apps/docs/content/development/publishable-api-keys/storefront/use-in-requests.md +++ b/www/apps/docs/content/development/publishable-api-keys/storefront/use-in-requests.md @@ -12,9 +12,9 @@ In this document, you'll learn how to use Publishable API Keys in client request ::: -## Default Behaviour In Product Store Endpoints +## Default Behaviour In Product Store API Routes -If you don't pass a publishable API Key for the store endpoints `/store/products` and `/store/products/{product_id}`, the default sales channel of the store is assigned to the request. +If you don't pass a publishable API Key for the store API Routes `/store/products` and `/store/products/{product_id}`, the default sales channel of the store is assigned to the request. --- diff --git a/www/apps/docs/content/development/search/create.md b/www/apps/docs/content/development/search/create.md index 6c62de34a3..2e80697266 100644 --- a/www/apps/docs/content/development/search/create.md +++ b/www/apps/docs/content/development/search/create.md @@ -321,11 +321,11 @@ class MySearchService extends AbstractSearchService { This method is used to search through an index by a query. -In the Medusa backend, this method is used within the [Search Products endpoint](https://docs.medusajs.com/api/store#products_postproductssearch) to retrieve the search results. +In the Medusa backend, this method is used within the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) to retrieve the search results. This method accepts the following parameters: -1. `indexName`: the first parameter is a string indicating the index to search through. When using the Search Products endpoint, the index is the default index defined in the `IndexName` static property of the `ProductService`, which is `products`. +1. `indexName`: the first parameter is a string indicating the index to search through. When using the Search Products API Route, the index is the default index defined in the `IndexName` static property of the `ProductService`, which is `products`. 2. `query`: the second parameter is a string indicating the query to use to search through the documents. 3. `options`: the third parameter is typically an object that can be used to pass any necessary options to the search engine. @@ -406,7 +406,7 @@ Run your backend to test it out: npx medusa develop ``` -You can then send a request to the [Search Products endpoint](https://docs.medusajs.com/api/store#products_postproductssearch) to see if your search service returns any results. +You can then send a request to the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) to see if your search service returns any results. --- diff --git a/www/apps/docs/content/development/search/overview.mdx b/www/apps/docs/content/development/search/overview.mdx index 68f5fc05c3..49d6519b4e 100644 --- a/www/apps/docs/content/development/search/overview.mdx +++ b/www/apps/docs/content/development/search/overview.mdx @@ -11,11 +11,11 @@ In this document, you’ll learn what a search service is and how it’s used in ## Overview -A search service is used to manage search indices of searchable items, such as products, and providing results for search operations. Although the Medusa core provides basic search functionalities through its endpoints, a search service allows you to integrate third-party services for an optimized search experience and rich search functionalities. +A search service is used to manage search indices of searchable items, such as products, and providing results for search operations. Although the Medusa core provides basic search functionalities through its API Routes, a search service allows you to integrate third-party services for an optimized search experience and rich search functionalities. A search service is a service class that is defined in a TypeScript or JavaScript file, which is created in the `src/services` directory of your Medusa backend codebase or plugin. The class must extend the `AbstractSearchService` class imported from the `@medusajs/utils` package. -Using the [dependency container and injection](../fundamentals/dependency-injection.md), the Medusa backend will then use and resolve the search service within the backend’s search operations, such as when the [Search Products](https://docs.medusajs.com/api/store#products_postproductssearch) endpoint is used. You can also [resolve the service](../services/create-service.mdx#use-a-service) within your resources to trigger the search where necessary. +Using the [dependency container and injection](../fundamentals/dependency-injection.md), the Medusa backend will then use and resolve the search service within the backend’s search operations, such as when the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) is used. You can also [resolve the service](../services/create-service.mdx#use-a-service) within your resources to trigger the search where necessary. Medusa provides official plugins that you can install and use in your Medusa backend. Check out available search plugins [here](../../plugins/search/index.mdx). diff --git a/www/apps/docs/content/development/services/create-service.mdx b/www/apps/docs/content/development/services/create-service.mdx index 011b67106a..e1fb64c1c2 100644 --- a/www/apps/docs/content/development/services/create-service.mdx +++ b/www/apps/docs/content/development/services/create-service.mdx @@ -1,5 +1,4 @@ --- -description: 'Learn how to create a service in Medusa. This guide also includes how to use services in other services, subscribers, and endpoints.' addHowToData: true --- @@ -18,7 +17,7 @@ To create a service, create a TypeScript or JavaScript file in `src/services` to For example, if you want to create a service `PostService`, eventually registered as `postService`, create the file `post.ts` in `src/services` with the following content: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts import { TransactionBaseService } from "@medusajs/medusa" class PostService extends TransactionBaseService { @@ -54,7 +53,7 @@ As the service extends the `TransactionBaseService` class, all resources registe So, if you want your service to use another service, add it as part of your constructor’s dependencies and set it to a field inside your service’s class: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts import { ProductService } from "@medusajs/medusa" import { PostRepository } from "../repositories/post" @@ -71,7 +70,7 @@ class PostService extends TransactionBaseService { Then, you can use that service anywhere in your custom service. For example: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts class PostService extends TransactionBaseService { // ... async getProductCount() { @@ -92,7 +91,7 @@ However, to actually get an instance of the repository within the service's meth For example: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts import { PostRepository } from "../repositories/post" class PostService extends TransactionBaseService { @@ -132,7 +131,7 @@ The data returned by the function passed as a parameter to the `atomicPhase_` me For example, the `PostService`'s `create` method with the `atomicPhase_` method: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts class PostService extends TransactionBaseService { protected postRepository_: typeof PostRepository // ... @@ -170,7 +169,7 @@ There are three lifetime types: You can set the lifetime of your service by setting the `LIFE_TIME` static property: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts import { TransactionBaseService } from "@medusajs/medusa" import { Lifetime } from "awilix" @@ -189,7 +188,7 @@ Within your service, you may need to access the Medusa configuration exported fr For example: -```ts title=/src/services/post.ts +```ts title=src/services/post.ts import { ConfigModule, TransactionBaseService, @@ -218,7 +217,7 @@ export default PostService ## Pagination, Filtering, and Relations -Often, your service will provide methods that retrieve a list of items, which can be used by endpoints. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by endpoints or any other resources utilizing this service. +Often, your service will provide methods that retrieve a list of items, which can be used by API Routes. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by API Routes or any other resources utilizing this service. The `@medusajs/medusa` package provides the following generic types that you can use to create the signature of your method that accepts filtering and pagination parameters: @@ -298,7 +297,7 @@ class PostService extends TransactionBaseService { } ``` -Then, any other resources such as endpoints or services that use this method can pass what relations to expand in the next parameter: +Then, any other resources such as API Route or services that use this method can pass what relations to expand in the next parameter: ```ts await postService.retrieve(id, { @@ -314,7 +313,7 @@ When you need to throw errors in your service methods, it's recommended to use ` :::note -This assumes you're handling errors in your custom endpoints as explained [here](../endpoints/create.mdx#handle-errors). +This assumes you're handling errors in your custom API Route as explained [here](../api-routes/create.mdx#handle-errors). ::: @@ -378,9 +377,9 @@ class MyService extends TransactionBaseService { } ``` -### In an Endpoint +### In an API Route -To use your custom service in an endpoint, you can use `req.scope.resolve` passing it the service’s registration name: +To use your custom service in an API Route, you can use `MedusaRequest` object's `scope.resolve` method passing it the service’s registration name: ```ts const postService = req.scope.resolve("postService") diff --git a/www/apps/docs/content/development/services/extend-service.mdx b/www/apps/docs/content/development/services/extend-service.mdx index 4925cc09ad..56fb6b1403 100644 --- a/www/apps/docs/content/development/services/extend-service.mdx +++ b/www/apps/docs/content/development/services/extend-service.mdx @@ -1,5 +1,4 @@ --- -description: 'Learn how to create a service in Medusa. This guide also includes how to use services in other services, subscribers, and endpoints.' addHowToData: true --- diff --git a/www/apps/docs/content/development/services/overview.mdx b/www/apps/docs/content/development/services/overview.mdx index fec7b3d7f2..fb21882e13 100644 --- a/www/apps/docs/content/development/services/overview.mdx +++ b/www/apps/docs/content/development/services/overview.mdx @@ -17,7 +17,7 @@ For example, you can use Medusa’s `productService` to get the list of products In the Medusa backend, custom services are TypeScript or JavaScript files located in the `src/services` directory. Each service should be a class that extends the `TransactionBaseService` class from the core Medusa package `@medusajs/medusa`. Each file you create in `src/services` should hold one service and export it. -The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered in the dependency container as the camel-case version of the file name with `Service` appended to the end of the name. Other resources, such as other services or endpoints, will use that name when resolving the service from the dependency container. +The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered in the dependency container as the camel-case version of the file name with `Service` appended to the end of the name. Other resources, such as other services or API Routes, will use that name when resolving the service from the dependency container. For example, if the file name is `hello.ts`, the service will be registered as `helloService` in the dependency container. If the file name is `hello-world.ts`, the service name will be registered as `helloWorldService`. diff --git a/www/apps/docs/content/development/strategies/override-strategy.md b/www/apps/docs/content/development/strategies/override-strategy.md index de46be0ffd..fe4e3cf8fb 100644 --- a/www/apps/docs/content/development/strategies/override-strategy.md +++ b/www/apps/docs/content/development/strategies/override-strategy.md @@ -11,7 +11,7 @@ In this document, you’ll learn how to override a strategy in a Medusa backend The Medusa core defines and uses strategies for certain functionalities, which allows developers to override these functionalities and implement them as fits for their use case. -For example, the cart completion process is implemented within a `CartCompletionStrategy` that is used inside the Complete Cart endpoint. If you need to change the cart completion process, you can override the `CartCompletionStrategy` and implement your own strategy. The Medusa backend will then use your strategy instead of the one defined in the core. +For example, the cart completion process is implemented within a `CartCompletionStrategy` that is used inside the Complete Cart API Route. If you need to change the cart completion process, you can override the `CartCompletionStrategy` and implement your own strategy. The Medusa backend will then use your strategy instead of the one defined in the core. ### Hierarchy of Strategy Resolution diff --git a/www/apps/docs/content/development/strategies/overview.mdx b/www/apps/docs/content/development/strategies/overview.mdx index e225f01242..5542c6fc13 100644 --- a/www/apps/docs/content/development/strategies/overview.mdx +++ b/www/apps/docs/content/development/strategies/overview.mdx @@ -15,9 +15,9 @@ A strategy is an isolated piece of business logic that can be overridden and cus For example, in the core `@medusajs/medusa` package, strategies are used to implement functionalities like cart completion and product import. -These strategy classes are then resolved in endpoints, services, or wherever needed using dependency injection and used to perform their designated functionality. +These strategy classes are then resolved in API Routes, services, or wherever needed using dependency injection and used to perform their designated functionality. -For example, the `CartCompletionStrategy` is resolved in the Complete Cart endpoint that is defined in the core `@medusajs/medusa` package. It’s then used to complete the cart and place the order: +For example, the `CartCompletionStrategy` is resolved in the Complete Cart API Route that is defined in the core `@medusajs/medusa` package. It’s then used to complete the cart and place the order: ```ts export default async (req, res) => { diff --git a/www/apps/docs/content/homepage.mdx b/www/apps/docs/content/homepage.mdx index bf01c42e3d..2a014d7b3a 100644 --- a/www/apps/docs/content/homepage.mdx +++ b/www/apps/docs/content/homepage.mdx @@ -160,6 +160,15 @@ Medusa provides the essential building blocks that developers can put together t Learn about all the new features and enhancements in Medusa. diff --git a/www/apps/docs/content/js-client/overview.md b/www/apps/docs/content/js-client/overview.md index 61214ec17d..b9e247e98b 100644 --- a/www/apps/docs/content/js-client/overview.md +++ b/www/apps/docs/content/js-client/overview.md @@ -89,7 +89,7 @@ You can follow [this guide](https://docs.medusajs.com/api/admin#authentication) ### Using cookies -Authentication using cookies is done automatically by Axios, which is used within the Medusa JS Client, when authenticating using the [auth](/references/js-client/classes/AuthResource) endpoints. After authentication, all subsequent calls will be authenticated. +Authentication using cookies is done automatically by Axios, which is used within the Medusa JS Client, when authenticating using the [auth](/references/js-client/classes/AuthResource) API Routes. After authentication, all subsequent calls will be authenticated. --- diff --git a/www/apps/docs/content/medusa-react/overview.mdx b/www/apps/docs/content/medusa-react/overview.mdx index 3a51641bda..44f40a0f5b 100644 --- a/www/apps/docs/content/medusa-react/overview.mdx +++ b/www/apps/docs/content/medusa-react/overview.mdx @@ -142,7 +142,7 @@ export default Products In the example above, you import the `useProducts` hook from `medusa-react`. This hook, and every other query hook exposed by `medusa-react`, returns everything that `useQuery` [returns in Tanstack Query](https://tanstack.com/query/v4/docs/react/reference/useQuery), except for the `data` field. -Instead of the `data` field, the response data is flattened and is part of the hooks’ returned fields. In the example above, the List Products endpoint returns a `products` array. So, `useProducts` returns a `products` array along with other fields returned by `useQuery`. +Instead of the `data` field, the response data is flattened and is part of the hooks’ returned fields. In the example above, the List Products API Route returns a `products` array. So, `useProducts` returns a `products` array along with other fields returned by `useQuery`. If the request accepts any parameters, they can be passed as parameters to the `mutate` request. For example: @@ -213,11 +213,11 @@ Learn more about how you can use mutations in [Tanstack Query’s documentation] ### Custom Hooks -Medusa React provides three utility hooks that allows developers to consume their admin custom endpoints using the same Medusa React methods and conventions. +Medusa React provides three utility hooks that allows developers to consume their admin custom API Routes using the same Medusa React methods and conventions. #### useAdminCustomQuery -The `useAdminCustomQuery` utility hook can be used to send a `GET` request to a custom endpoint in your Medusa backend and retrieve data. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body: +The `useAdminCustomQuery` utility hook can be used to send a `GET` request to a custom API Route in your Medusa backend and retrieve data. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body: ```ts useAdminCustomQuery @@ -225,9 +225,9 @@ useAdminCustomQuery The hook accepts the following parameters: -1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. +1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. 2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When a mutation related to this same key succeeds, the key will be automatically invalidated. -3. `query`: (optional) the third parameter is an object that can be used to pass query parameters to the endpoint. For example, if you want to pass an `expand` query parameter you can pass it within this object. Each query parameter's name is a key in the object. There are no limitations on what the type of the value can be, so you can pass an array or simply a string as a value. +3. `query`: (optional) the third parameter is an object that can be used to pass query parameters to the API Route. For example, if you want to pass an `expand` query parameter you can pass it within this object. Each query parameter's name is a key in the object. There are no limitations on what the type of the value can be, so you can pass an array or simply a string as a value. 4. `options`: (optional) the fourth parameter is an object of [TanStack Query options](https://tanstack.com/query/v4/docs/react/reference/useQuery). The request returns an object containing keys like `data` which is an object that includes the data returned in the response, and `isLoading` which is a boolean value indicating whether the request is still in progress. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useQuery). @@ -343,7 +343,7 @@ export default AuthorsBlogPosts #### useAdminCustomPost -The `useAdminCustomPost` utility hook can be used to send a `POST` request to a custom endpoint in your Medusa backend. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body: +The `useAdminCustomPost` utility hook can be used to send a `POST` request to a custom API Route in your Medusa backend. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body: ```ts useAdminCustomPost @@ -351,9 +351,9 @@ useAdminCustomPost The hook accepts the following parameters: -1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. +1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. 2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When the mutation succeeds, the key will be automatically invalidated. -3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom endpoint is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched. +3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom API Route is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched. 4. `options`: (optional) the fourth parameter is an object of [Mutation options](https://tanstack.com/query/v4/docs/react/reference/useMutation). The request returns an object containing keys like `mutation` which is a function that can be used to send the `POST` request at a later point. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useMutation). @@ -421,7 +421,7 @@ export default CreateBlogPost #### useAdminCustomDelete -The `useAdminCustomDelete` utility hook can be used to send a `DELETE` request to a custom endpoint in your Medusa backend. It's a generic function, so you can pass a type for the expected response if you're using TypeScript in your development: +The `useAdminCustomDelete` utility hook can be used to send a `DELETE` request to a custom API Route in your Medusa backend. It's a generic function, so you can pass a type for the expected response if you're using TypeScript in your development: ```ts useAdminCustomDelete @@ -429,9 +429,9 @@ useAdminCustomDelete The hook accepts the following parameters: -1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. +1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically. 2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When the mutation succeeds, the key will be automatically invalidated. -3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom endpoint is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched. +3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom API Route is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched. 4. `options`: (optional) the fourth parameter is an object of [Mutation options](https://tanstack.com/query/v4/docs/react/reference/useMutation). The request returns an object containing keys like `mutation` which is a function that can be used to send the `DELETE` request at a later point. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useMutation). diff --git a/www/apps/docs/content/modules/carts-and-checkout/backend/add-fulfillment-provider.md b/www/apps/docs/content/modules/carts-and-checkout/backend/add-fulfillment-provider.md index c44524a1f0..d655f9fe29 100644 --- a/www/apps/docs/content/modules/carts-and-checkout/backend/add-fulfillment-provider.md +++ b/www/apps/docs/content/modules/carts-and-checkout/backend/add-fulfillment-provider.md @@ -162,13 +162,13 @@ class MyFulfillmentService extends AbstractFulfillmentService { ### getFulfillmentOptions -This method is used when retrieving the list of fulfillment options available in a region, particularly by the [List Fulfillment Options endpoint](https://docs.medusajs.com/api/admin#regions_getregionsregionfulfillmentoptions). +This method is used when retrieving the list of fulfillment options available in a region, particularly by the [List Fulfillment Options API Route](https://docs.medusajs.com/api/admin#regions_getregionsregionfulfillmentoptions). For example, if you’re integrating UPS as a fulfillment provider, you might support two fulfillment options: UPS Express Shipping and UPS Access Point. Each of these options can have different data associated with them. This method is expected to return an array of options. These options don't have any required format. -Later on, these options can be used when creating a shipping option, such as when using the [Create Shipping Option endpoint](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions). The chosen fulfillment option, which is one of the items in the array returned by this method, will be set in the `data` object of the shipping option. +Later on, these options can be used when creating a shipping option, such as when using the [Create Shipping Option API Route](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions). The chosen fulfillment option, which is one of the items in the array returned by this method, will be set in the `data` object of the shipping option. For example: @@ -190,7 +190,7 @@ class MyFulfillmentService extends AbstractFulfillmentService { ### validateOption -Once the admin creates the shipping option, the data of the shipping option will be validated first using this method. This method is called when the [Create Shipping Option endpoint](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions) is used. +Once the admin creates the shipping option, the data of the shipping option will be validated first using this method. This method is called when the [Create Shipping Option API Route](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions) is used. This method accepts the `data` object that is sent in the body of the request, basically, the `data` object of the shipping option. You can use this data to validate the shipping option before it is saved. @@ -223,7 +223,7 @@ This method accepts three parameters: You can use these parameters to validate the chosen shipping option. For example, you can check if the `data` object passed as a second parameter includes all data needed to fulfill the shipment later on. -If any of the data is invalid, you can throw an error. This error will stop Medusa from creating a shipping method and the error message will be returned as a result to the endpoint. +If any of the data is invalid, you can throw an error. This error will stop Medusa from creating a shipping method and the error message will be returned as a result of the API Route. If everything is valid, this method must return an object that will be stored in the `data` property of the shipping method to be created. So, make sure the value you return contains everything you need to fulfill the shipment later on. diff --git a/www/apps/docs/content/modules/carts-and-checkout/backend/add-payment-provider.md b/www/apps/docs/content/modules/carts-and-checkout/backend/add-payment-provider.md index b75f73b55f..5e07f15805 100644 --- a/www/apps/docs/content/modules/carts-and-checkout/backend/add-payment-provider.md +++ b/www/apps/docs/content/modules/carts-and-checkout/backend/add-payment-provider.md @@ -510,7 +510,7 @@ class MyPaymentService extends AbstractPaymentProcessor { This method is used to capture the payment amount of an order. This is typically triggered manually by the store operator from the admin. -This method is also used for capturing payments of a swap of an order, or when the [Capture Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture) endpoint is called. +This method is also used for capturing payments of a swap of an order, or when a request is sent to the [Capture Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture). You can utilize this method to interact with the third-party provider and perform any actions necessary to capture the payment. @@ -538,7 +538,7 @@ class MyPaymentService extends AbstractPaymentProcessor { This method is used to refund an order’s payment. This is typically triggered manually by the store operator from the admin. The refund amount might be the total order amount or part of it. -This method is also used for refunding payments of a swap or a claim of an order, or when the [Refund Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds) endpoint is called. +This method is also used for refunding payments of a swap or a claim of an order, or when a request is sent to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds). You can utilize this method to interact with the third-party provider and perform any actions necessary to refund the payment. diff --git a/www/apps/docs/content/modules/carts-and-checkout/backend/cart-completion-strategy.md b/www/apps/docs/content/modules/carts-and-checkout/backend/cart-completion-strategy.md index 6b858dd6c8..62080df75e 100644 --- a/www/apps/docs/content/modules/carts-and-checkout/backend/cart-completion-strategy.md +++ b/www/apps/docs/content/modules/carts-and-checkout/backend/cart-completion-strategy.md @@ -85,7 +85,7 @@ In the above example, you inject the `IdempotencyKeyService` in the constructor. ## Step 2: Implement the complete Method -The cart completion strategy is required to implement a single method: the `complete` method. This method is used in the [Complete Cart endpoint](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) to handle the logic of completing the cart. +The cart completion strategy is required to implement a single method: the `complete` method. This method is used in the [Complete Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) to handle the logic of completing the cart. The method accepts three parameters: @@ -120,7 +120,7 @@ Run your backend to test it out: npx medusa develop ``` -Then, try out your strategy using the Complete Cart endpoint. You should see the logic you implemented used for completing the cart. +Then, try out your strategy using the Complete Cart API Route. You should see the logic you implemented used for completing the cart. --- diff --git a/www/apps/docs/content/modules/carts-and-checkout/cart.md b/www/apps/docs/content/modules/carts-and-checkout/cart.md index 32e6e45527..d7774e9875 100644 --- a/www/apps/docs/content/modules/carts-and-checkout/cart.md +++ b/www/apps/docs/content/modules/carts-and-checkout/cart.md @@ -63,7 +63,7 @@ The cart’s totals are retrieved by default in all the [cart’s store APIs](ht The cart completion functionality is implemented inside the strategy `cartCompletionStrategy`. This allows you to customize how the process is implemented in your store. -You can initiate the cart completion process by sending a request to the [Complete Cart endpoint](https://docs.medusajs.com/api/store#carts_postcartscartcomplete). +You can initiate the cart completion process by sending a request to the [Complete Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete). ### Idempotency Key diff --git a/www/apps/docs/content/modules/carts-and-checkout/storefront/implement-checkout-flow.mdx b/www/apps/docs/content/modules/carts-and-checkout/storefront/implement-checkout-flow.mdx index 5e55fc9334..fea8662d9b 100644 --- a/www/apps/docs/content/modules/carts-and-checkout/storefront/implement-checkout-flow.mdx +++ b/www/apps/docs/content/modules/carts-and-checkout/storefront/implement-checkout-flow.mdx @@ -60,7 +60,7 @@ In this step, the customer generally enters their shipping info, then chooses th ### Add Shipping Address -After the customer enters their shipping address information, you must send a `POST` request to the [Update a Cart](https://docs.medusajs.com/api/store#carts_postcartscart) API endpoint: +After the customer enters their shipping address information, you must send a `POST` request to the [Update a Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscart): @@ -164,7 +164,7 @@ The request returns the updated cart, with the new shipping address available in After updating the cart with the customer’s address, the list of available [shipping options](../shipping.md#shipping-option) for that cart might change. So, you should retrieve the updated list of options. -You can retrieve the list of shipping options by sending a `GET` request to the [Retrieve Shipping Options for Cart API](https://docs.medusajs.com/api/store#shipping-options_getshippingoptionscartid) endpoint: +You can retrieve the list of shipping options by sending a `GET` request to the [Retrieve Shipping Options for Cart API Route](https://docs.medusajs.com/api/store#shipping-options_getshippingoptionscartid): @@ -234,7 +234,7 @@ The request accepts the ID of the cart as a path parameter. It returns the array ### Choose Shipping Option -Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method](https://docs.medusajs.com/api/store#carts_postcartscartshippingmethod) API endpoint. This will create a [shipping method](../shipping.md#shipping-method) based on the shipping option chosen and will associate it with the customer’s cart: +Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method API Route](https://docs.medusajs.com/api/store#carts_postcartscartshippingmethod). This will create a [shipping method](../shipping.md#shipping-method) based on the shipping option chosen and will associate it with the customer’s cart: @@ -308,7 +308,7 @@ In this step, the customer generally chooses a payment method to complete their When the page opens and before the payment providers are displayed to the customer to choose from, you must create the [payment sessions](../payment.md#payment-session) for the current cart. Each payment provider will have a payment session associated with it. These payment sessions will be used later when the customer chooses the payment provider they want to complete their purchase with. -To initialize the payment sessions, send a `POST` request to the [Initialize Payment Sessions](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession) API endpoint: +To initialize the payment sessions, send a `POST` request to the [Initialize Payment Sessions API Route](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession): @@ -372,11 +372,11 @@ fetch(`/store/carts/${cartId}/payment-sessions`, { -This endpoint accepts the ID of the cart as a path parameter. It returns the updated cart with the initialized payment sessions available on `cart.payment_sessions`. +This API Route accepts the ID of the cart as a path parameter. It returns the updated cart with the initialized payment sessions available on `cart.payment_sessions`. ### Select Payment Session -When the customer chooses the payment processor they want to complete purchase with, you should select the payment session associated with that payment processor. To do that, send a `POST` request to the [Select a Payment Session](https://docs.medusajs.comapi/store#carts_postcartscartpaymentsession) API endpoint: +When the customer chooses the payment processor they want to complete purchase with, you should select the payment session associated with that payment processor. To do that, send a `POST` request to the [Select a Payment Session API Route](https://docs.medusajs.comapi/store#carts_postcartscartpaymentsession): @@ -451,7 +451,7 @@ If you have one payment processor or if only one payment processor is available This step is optional and is only necessary for some payment processors. As mentioned in the [Payment Architecture](../payment.md#overview) documentation, the `PaymentSession` model has a `data` attribute that holds any data required for the Payment Processor to perform payment operations such as capturing payment. -If you need to update that data at any point before the purchase is made, send a request to [Update a Payment Session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate) API endpoint: +If you need to update that data at any point before the purchase is made, send a request to [Update a Payment Session API Route](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate): @@ -537,7 +537,7 @@ It returns the updated cart. You can access the payment session's data on `cart. The last step is to place the order by completing the cart. When you complete the cart, your Medusa backend will try to authorize the payment first, then place the order if the authorization is successful. So, you should perform any necessary action with your payment processor first to make sure the authorization is successful when you send the request to complete the cart. -To complete a cart, send a `POST` request to the [Complete a Cart](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) API endpoint: +To complete a cart, send a `POST` request to the [Complete a Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete): diff --git a/www/apps/docs/content/modules/customers/admin/manage-customer-groups.mdx b/www/apps/docs/content/modules/customers/admin/manage-customer-groups.mdx index 748e99996a..0d4e3416c8 100644 --- a/www/apps/docs/content/modules/customers/admin/manage-customer-groups.mdx +++ b/www/apps/docs/content/modules/customers/admin/manage-customer-groups.mdx @@ -48,7 +48,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## Create Customer Groups -You can create a customer group by sending a request to the Create Customer Group endpoint: +You can create a customer group by sending a request to the Create Customer Group API Route: @@ -131,7 +131,7 @@ This request requires the `name` parameter and optionally accepts the `metadata` ## List Customer Groups -You can get a list of all customer groups by sending a request to the List Customer Groups endpoint: +You can get a list of all customer groups by sending a request to the List Customer Groups API Route: @@ -212,7 +212,7 @@ You can also pass filters and other selection query parameters to the request. C ## Retrieve a Customer Group -You can retrieve a single customer group by sending a request to the Get a Customer Group endpoint: +You can retrieve a single customer group by sending a request to the Get a Customer Group API Route: @@ -279,7 +279,7 @@ This request accepts the ID of the customer group to retrieve as a path paramete ## Update a Customer Group -You can update a customer group’s data by sending a request to the Update Customer Group endpoint: +You can update a customer group’s data by sending a request to the Update Customer Group API Route: @@ -373,7 +373,7 @@ This request accepts the ID of the customer group as a path parameter, and optio ## Delete Customer Group -You can delete a customer group by sending a request to the Delete a Customer Group endpoint: +You can delete a customer group by sending a request to the Delete a Customer Group API Route: @@ -443,7 +443,7 @@ This request accepts the ID of the customer group to delete as a path parameter. ### Add Customer to Group -You can add a customer to a group by sending a request to the Customer Group’s Add Customer endpoint: +You can add a customer to a group by sending a request to the Customer Group’s Add Customer API Route: @@ -543,7 +543,7 @@ This request accepts the ID of the customer group as a path parameter. In its bo ### List Customers -You can retrieve a list of all customers in a customer group using the List Customers endpoint: +You can retrieve a list of all customers in a customer group using the List Customers API Route: @@ -626,7 +626,7 @@ Removing customers from a group does not remove them entirely. They’ll still b ::: -You can remove customers from a customer group by sending a request to the Remove Customers endpoint: +You can remove customers from a customer group by sending a request to the Remove Customers API Route: diff --git a/www/apps/docs/content/modules/customers/admin/manage-customers.mdx b/www/apps/docs/content/modules/customers/admin/manage-customers.mdx index 9d66c355c1..c882e37d49 100644 --- a/www/apps/docs/content/modules/customers/admin/manage-customers.mdx +++ b/www/apps/docs/content/modules/customers/admin/manage-customers.mdx @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Customers -You can show a list of customers by sending a request to the [List Customers](https://docs.medusajs.com/api/admin#customers_getcustomers) endpoint: +You can show a list of customers by sending a request to the [List Customers API Route](https://docs.medusajs.com/api/admin#customers_getcustomers): @@ -139,7 +139,7 @@ You can learn more about pagination in the [API reference](https://docs.medusajs Admins can create customer accounts. They have to supply the customer’s credentials and basic info. -You can create a customer account by sending a request to the [Create a Customer](https://docs.medusajs.com/api/admin#customers_postcustomers) endpoint: +You can create a customer account by sending a request to the [Create a Customer API Route](https://docs.medusajs.com/api/admin#customers_postcustomers): @@ -246,7 +246,7 @@ The request returns the created customer object in the response. An admin can edit a customer’s basic information and credentials. -You can edit a customer’s information by sending a request to the [Update a Customer](https://docs.medusajs.com/api/admin#customers_postcustomerscustomer) endpoint: +You can edit a customer’s information by sending a request to the [Update a Customer API Route](https://docs.medusajs.com/api/admin#customers_postcustomerscustomer): diff --git a/www/apps/docs/content/modules/customers/storefront/implement-customer-profiles.mdx b/www/apps/docs/content/modules/customers/storefront/implement-customer-profiles.mdx index e2d448fa9c..136ca16221 100644 --- a/www/apps/docs/content/modules/customers/storefront/implement-customer-profiles.mdx +++ b/www/apps/docs/content/modules/customers/storefront/implement-customer-profiles.mdx @@ -12,7 +12,7 @@ In this document, you’ll learn how to implement customer account functionaliti ## Overview -Medusa provides the necessary functionalities and endpoints to allow integrating essential customer features. Customers can create accounts to manage their information and keep track of their orders. +Medusa provides the necessary functionalities and API Routes to allow integrating essential customer features. Customers can create accounts to manage their information and keep track of their orders. ### Scenario @@ -58,7 +58,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus A customer can register with an email and a password to store and manage their data. -You can register a new customer by sending a request to the [Create a Customer](https://docs.medusajs.com/api/store#customers_postcustomers) endpoint: +You can register a new customer by sending a request to the [Create a Customer API Route](https://docs.medusajs.com/api/store#customers_postcustomers): @@ -135,7 +135,7 @@ fetch(`/store/customers`, { This request requires the following body parameters: -- `email`: An email used to log in after registration. This email must be unique. You can check if an email is unique using the “[Check if email exists](https://docs.medusajs.com/api/store#auth_getauthemail)” endpoint. +- `email`: An email used to log in after registration. This email must be unique. You can check if an email is unique using the “[Check if email exists](https://docs.medusajs.com/api/store#auth_getauthemail)” API Route. - `password`: A password used to log in after registration. - `first_name`: The customer’s first name. - `last_name`: The customer’s last name. @@ -150,7 +150,7 @@ It returns the created customer object in the response. A customer can log in to your store to manage their data and make purchases using their account. -You can log in a customer into your store by sending a request to the [Customer Login](https://docs.medusajs.com/api/store#auth_postauth) endpoint: +You can log in a customer into your store by sending a request to the [Customer Login API Route](https://docs.medusajs.com/api/store#auth_postauth): @@ -199,7 +199,7 @@ However, if you’re using the Fetch API, you must include the option `credentia ## Log out a Customer -You can log out a customer by sending a request to the [Customer Logout](https://docs.medusajs.com/api/store#auth_deleteauth) endpoint: +You can log out a customer by sending a request to the [Customer Logout API Route](https://docs.medusajs.com/api/store#auth_deleteauth): @@ -239,7 +239,7 @@ Customers might need to reset their password in case they forget it. To reset a The customer must first enter their account’s email. Then, if an account with that email address exists, an email will be sent to that email address with a link that points the customer to step 2. -You can request to reset a customer’s password by sending a request to the [Request Password Reset](https://docs.medusajs.com/api/store#customers_postcustomerscustomerpasswordtoken) endpoint: +You can request to reset a customer’s password by sending a request to the [Request Password Reset API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomerpasswordtoken): @@ -295,7 +295,7 @@ If the customer doesn’t receive an email after this request, make sure that yo After the first step, the customer should receive an email with a link to a page in the storefront. This page should accept a `token` query parameter. Then, the customer should be prompted to enter their email and password. -You can then reset the customer’s password to the new password they enter by sending a request to the [Reset Password](https://docs.medusajs.com/api/store#customers_postcustomersresetpassword) endpoint: +You can then reset the customer’s password to the new password they enter by sending a request to the [Reset Password API Route](https://docs.medusajs.com/api/store#customers_postcustomersresetpassword): @@ -350,7 +350,7 @@ If successful, this request returns the customer object in the response. A logged-in customer can edit their info, such as their first name or email address. -You can edit a customer’s info using the [Update Customer](https://docs.medusajs.com/api/store#customers_postcustomerscustomer) endpoint: +You can edit a customer’s info using the [Update Customer API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomer): @@ -435,7 +435,7 @@ The customer object returned in the requests mentioned in this document include ### Add a Shipping Address -You can add a shipping address to a customer’s account by sending a request to the [Add a Shipping Address](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddresses) endpoint: +You can add a shipping address to a customer’s account by sending a request to the [Add a Shipping Address API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddresses): @@ -511,7 +511,7 @@ This request returns the updated customer object in the response. ### Edit a Shipping Address -You can edit a customer’s shipping address using the [Update a Shipping Address](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddressesaddress) endpoint: +You can edit a customer’s shipping address using the [Update a Shipping Address API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddressesaddress): @@ -556,7 +556,7 @@ This request returns the updated customer object in the response. ### Delete a Shipping Address -You can delete a shipping address by sending a request to the [Delete an Address](https://docs.medusajs.com/api/store#customers_deletecustomerscustomeraddressesaddress) endpoint: +You can delete a shipping address by sending a request to the [Delete an Address API Route](https://docs.medusajs.com/api/store#customers_deletecustomerscustomeraddressesaddress): @@ -595,7 +595,7 @@ This request requires the address’s ID as a path parameter. It returns in the Logged-in customers can see their orders along with the orders’ details. -You can retrieve a customer’s orders by sending a request to the [List Orders](https://docs.medusajs.com/api/store#customers_getcustomerscustomerorders) endpoint: +You can retrieve a customer’s orders by sending a request to the [List Orders API Route](https://docs.medusajs.com/api/store#customers_getcustomerscustomerorders): diff --git a/www/apps/docs/content/modules/discounts/admin/manage-discounts.mdx b/www/apps/docs/content/modules/discounts/admin/manage-discounts.mdx index a8d4356208..6887ae9977 100644 --- a/www/apps/docs/content/modules/discounts/admin/manage-discounts.mdx +++ b/www/apps/docs/content/modules/discounts/admin/manage-discounts.mdx @@ -64,7 +64,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## Create a Discount -You can create a discount by sending a request to the [Create Discount](https://docs.medusajs.com/api/admin#discounts_postdiscounts) endpoint: +You can create a discount by sending a request to the [Create Discount API Route](https://docs.medusajs.com/api/admin#discounts_postdiscounts): @@ -202,7 +202,7 @@ This request returns the full `discount` object. ## Update Discount -You can update any of the discount’s information, configurations, and conditions by sending a request to the [Update Discount](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscount) endpoint. +You can update any of the discount’s information, configurations, and conditions by sending a request to the [Update Discount API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscount). For example, you can update the discount’s description and status by sending the following request: @@ -294,7 +294,7 @@ You can learn more about conditions and conditions types in the [Discount Archit ::: -You can send a request to the [Create Condition](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditions) endpoint to create a condition in a discount: +You can send a request to the [Create Condition API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditions) to create a condition in a discount: @@ -407,7 +407,7 @@ This request returns the full `discount` object in the response which includes a ### Retrieve Condition -You can retrieve a condition and its resources by sending a request to the [Get Condition](https://docs.medusajs.com/api/admin#discounts_getdiscountsdiscountconditionscondition) endpoint: +You can retrieve a condition and its resources by sending a request to the [Get Condition API Route](https://docs.medusajs.com/api/admin#discounts_getdiscountsdiscountconditionscondition): @@ -506,7 +506,7 @@ In the previous example, you pass `expand=products` as a query parameter, which ### Update Condition -You can update a condition’s resources using the [Update Condition](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditionscondition) endpoint. You can’t update a condition’s operator. +You can update a condition’s resources using the [Update Condition API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditionscondition). You can’t update a condition’s operator. For example, to update the products in a condition: @@ -608,7 +608,7 @@ This request returns the full `discount` object with the updated condition in th ### Delete Condition -You can delete a condition by sending a request to the [Delete Condition](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscountconditionscondition) endpoint: +You can delete a condition by sending a request to the [Delete Condition API Route](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscountconditionscondition): @@ -683,7 +683,7 @@ It returns the `discount` object in the response. ## Delete Discount -You can delete a discount by sending a request to the [Delete Discount](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscount) endpoint: +You can delete a discount by sending a request to the [Delete Discount API Route](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscount): diff --git a/www/apps/docs/content/modules/gift-cards/admin/manage-gift-cards.mdx b/www/apps/docs/content/modules/gift-cards/admin/manage-gift-cards.mdx index 33cb00f8fd..646aebd75d 100644 --- a/www/apps/docs/content/modules/gift-cards/admin/manage-gift-cards.mdx +++ b/www/apps/docs/content/modules/gift-cards/admin/manage-gift-cards.mdx @@ -59,11 +59,11 @@ You can learn more about [authenticating as an admin user in the API reference]( This section covers managing the gift card products. Each gift card can have unlimited denominations. -As gift cards are, before purchase, essentially products, you’ll be using product endpoints to manage them. +As gift cards are, before purchase, essentially products, you’ll be using product API Routes to manage them. ### Retrieve Gift Card Product -You can retrieve the gift card products by sending a request to the [List Products](https://docs.medusajs.com/api/admin#products_getproducts) endpoint, but filtering the products with the `is_giftcard` flag: +You can retrieve the gift card products by sending a request to the [List Products API Route](https://docs.medusajs.com/api/admin#products_getproducts), but filtering the products with the `is_giftcard` flag: @@ -146,13 +146,13 @@ curl -L -X GET '/admin/products?is_giftcard=true' \ -The List Products endpoint accepts a variety of query parameters that can be used to filter the products. One of them is `is_giftcard`. When set to `true`, it will only retrieve the gift card products. +The List Products API Route accepts a variety of query parameters that can be used to filter the products. One of them is `is_giftcard`. When set to `true`, it will only retrieve the gift card products. The request returns the `products` array in the response which holds the gift card in it, if it’s available. It also returns [pagination fields](https://docs.medusajs.com/api/admin#pagination). ### Create Gift Card Product -You can create a gift card product by sending a request to the [Create a Product](https://docs.medusajs.com/api/admin#products_postproducts) endpoint: +You can create a gift card product by sending a request to the [Create a Product API Route](https://docs.medusajs.com/api/admin#products_postproducts): @@ -353,7 +353,7 @@ Although you can create an unlimited number of gift cards, the admin dashboard's After creating a gift card, merchants can update it or its denomination. -You can update a gift card product’s details by sending a request to the [Update a Product](https://docs.medusajs.com/api/admin#products_postproductsproduct) endpoint: +You can update a gift card product’s details by sending a request to the [Update a Product API Route](https://docs.medusajs.com/api/admin#products_postproductsproduct): @@ -432,7 +432,7 @@ This request returns the updated gift card product in the response. ### Delete Gift Card Product -You can delete a gift card product by sending a request to the [Delete a Product](https://docs.medusajs.com/api/admin#products_deleteproductsproduct) endpoint: +You can delete a gift card product by sending a request to the [Delete a Product API Route](https://docs.medusajs.com/api/admin#products_deleteproductsproduct): @@ -505,7 +505,7 @@ This section covers how to manage custom gift cards. You can create an unlimited ### List Custom Gift Cards -You can retrieve all custom gift cards by sending a request to the [List Gift Cards](https://docs.medusajs.com/api/admin#gift-cards_getgiftcards) endpoint: +You can retrieve all custom gift cards by sending a request to the [List Gift Cards API Route](https://docs.medusajs.com/api/admin#gift-cards_getgiftcards): @@ -579,7 +579,7 @@ This request returns an array of `gift_cards` and [pagination fields](https://do Merchants can create custom gift cards to send a reward or gift to the customer. -You can create a custom gift card by sending a request to the [Create a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_postgiftcards) endpoint: +You can create a custom gift card by sending a request to the [Create a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_postgiftcards): @@ -664,7 +664,7 @@ This request returns the created gift card object in the response. Merchants can update any of the gift card’s properties, except for the value of the gift card. -You can update a gift card by sending a request to the [Update a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_postgiftcardsgiftcard) endpoint: +You can update a gift card by sending a request to the [Update a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_postgiftcardsgiftcard): @@ -745,7 +745,7 @@ This request returns the updated gift card object in the response. ### Delete Custom Gift Card -You can delete a custom gift card by sending a request to the [Delete a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_deletegiftcardsgiftcard) endpoint: +You can delete a custom gift card by sending a request to the [Delete a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_deletegiftcardsgiftcard): diff --git a/www/apps/docs/content/modules/gift-cards/storefront/use-gift-cards.mdx b/www/apps/docs/content/modules/gift-cards/storefront/use-gift-cards.mdx index 162ab859fe..f011f21150 100644 --- a/www/apps/docs/content/modules/gift-cards/storefront/use-gift-cards.mdx +++ b/www/apps/docs/content/modules/gift-cards/storefront/use-gift-cards.mdx @@ -58,7 +58,7 @@ In addition, this document doesn't cover how to implement checkout functionality Customers should be able to view gift cards before they make the purchase. Gift cards are essentially products like any other. -You can retrieve the gift card product using the [List Products](https://docs.medusajs.com/api/store#products_getproducts) endpoint, but passing it the `is_giftcard` query parameter: +You can retrieve the gift card product using the [List Products API Route](https://docs.medusajs.com/api/store#products_getproducts), but passing it the `is_giftcard` query parameter: @@ -147,7 +147,7 @@ The value of each denomination (or variant) is under the `prices` array. If you After the customer purchases the gift card, they’ll receive a code to redeem that gift card. Using that code, the customer can also view the details of that gift card. -You can retrieve the details of a gift card by sending a request to the [Get Gift Card by Code](https://docs.medusajs.com/api/store#gift-cards_getgiftcardscode) endpoint: +You can retrieve the details of a gift card by sending a request to the [Get Gift Card by Code API Route](https://docs.medusajs.com/api/store#gift-cards_getgiftcardscode): @@ -222,7 +222,7 @@ You can learn what other properties are available in the returned gift card obje A customer can redeem more than one gift card during checkout. The cart’s totals will then be adjusted based on the applied gift card. The gift card’s amount isn’t actually used until the order is placed. -You can redeem a gift card during checkout by sending a request to the [Update Cart](https://docs.medusajs.com/api/store#carts_postcartscart) endpoint: +You can redeem a gift card during checkout by sending a request to the [Update Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscart): @@ -306,7 +306,7 @@ To add gift cards, you must pass the array `gift_cards`. Each item in the array :::tip -The parameters passed in the update endpoint replace existing values. So, if you previously added a gift card, then tried adding another, you must include both in the `gift_cards` array. +The parameters passed to the update API Route replace existing values. So, if you previously added a gift card, then tried adding another, you must include both in the `gift_cards` array. ::: diff --git a/www/apps/docs/content/modules/multiwarehouse/admin/manage-inventory-items.mdx b/www/apps/docs/content/modules/multiwarehouse/admin/manage-inventory-items.mdx index 0830f8bfaa..ee07edff0a 100644 --- a/www/apps/docs/content/modules/multiwarehouse/admin/manage-inventory-items.mdx +++ b/www/apps/docs/content/modules/multiwarehouse/admin/manage-inventory-items.mdx @@ -57,7 +57,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Inventory Items -You can list inventory items by sending a request to the [List Inventory Items endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems): +You can list inventory items by sending a request to the [List Inventory Items API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems): @@ -126,7 +126,7 @@ curl -L -X GET '/admin/inventory-items' \ -This endpoint does not require any path or query parameters. You can, however, pass path parameters to search or filter inventory items. For example, you can get inventory items in a specific location by passing the `location_id` query parameter. You can learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems). +This API Route doesn't require any path or query parameters. You can, however, pass path parameters to search or filter inventory items. For example, you can get inventory items in a specific location by passing the `location_id` query parameter. You can learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems). This request returns an array of inventory item objects. @@ -140,7 +140,7 @@ Inventory items are automatically created when a variant is created with `manage ::: -You can create an inventory item by sending a request to the [Create Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems): +You can create an inventory item by sending a request to the [Create Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems): @@ -211,7 +211,7 @@ curl -L -X POST '/admin/inventory-items' \ -This endpoint requires in the body parameter the `variant_id` parameter, which is the ID of the variant to create this inventory item for. You can also pass other inventory-related parameters, such as `sku`. You can learn more about other available parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems). +This API Route requires in the body parameter the `variant_id` parameter, which is the ID of the variant to create this inventory item for. You can also pass other inventory-related parameters, such as `sku`. You can learn more about other available parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems). This request returns the created inventory item as an object. @@ -219,7 +219,7 @@ This request returns the created inventory item as an object. ## Retrieve Inventory Item -You can retrieve an inventory item by sending a request to the [Get Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitem): +You can retrieve an inventory item by sending a request to the [Get Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitem): @@ -281,7 +281,7 @@ curl -L -X GET '/admin/inventory-items/' \ -This endpoint accepts the ID of the inventory item as a path parameter. You can also path query parameters such as [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields). +This API Route accepts the ID of the inventory item as a path parameter. You can also path query parameters such as [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields). The request returns the inventory item as an object. @@ -289,7 +289,7 @@ The request returns the inventory item as an object. ## Update Inventory Item -You can update an inventory item by sending a request to the [Update Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem): +You can update an inventory item by sending a request to the [Update Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem): @@ -364,7 +364,7 @@ curl -L -X POST '/admin/inventory-items/' \ -This endpoint requires the inventory item’s ID as a path parameter. You can pass any of the inventory item’s attributes that you want to update in its body parameter. The example above updates the value of the `origin_country` attribute. You can learn more about available body parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem). +This API Route requires the inventory item’s ID as a path parameter. You can pass any of the inventory item’s attributes that you want to update in its body parameter. The example above updates the value of the `origin_country` attribute. You can learn more about available body parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem). The request returns the updated inventory item as an object. @@ -376,7 +376,7 @@ This section shows you the different ways you can manage inventory levels. Each ### List inventory levels -You can list inventory levels of an inventory item by sending a request to the [List inventory levels endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitemlocationlevels): +You can list inventory levels of an inventory item by sending a request to the [List inventory levels API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitemlocationlevels): @@ -445,13 +445,13 @@ curl -L -X GET '/admin/inventory-items//location-levels' \ -This endpoint requires the ID of the inventory item as a path parameter. You can also pass [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields) query parameters. +This API Route requires the ID of the inventory item as a path parameter. You can also pass [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields) query parameters. The request returns the inventory item as an object. In that object, the list of inventory levels are available under the property `location_levels`. ### Create Inventory Level -You can create a location level by sending a request to the [Create Inventory Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevels): +You can create a location level by sending a request to the [Create Inventory Level API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevels): @@ -533,7 +533,7 @@ curl -L -X POST '/admin/inventory-items//location-levels' -This endpoint requires the inventory item ID as a path parameter. In the request body, it requires the following parameters: +This API Route requires the inventory item ID as a path parameter. In the request body, it requires the following parameters: - `location_id`: The ID of the location associated with this location level. This ID is typically available through using the stock location module. - `stocked_quantity`: A number indicating the item’s quantity in stock. @@ -544,7 +544,7 @@ This request returns the inventory item associated with the created location lev ### Update Location Level -You can update a location level by sending a request to the [Update Location Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevelslocationlevel): +You can update a location level by sending a request to the [Update Location Level API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevelslocationlevel): @@ -624,7 +624,7 @@ curl -L -X POST '/admin/inventory-items//location-levels/< -This endpoint requires two path parameters: the first one being the ID of the inventory item, and the second one being the ID of the location. +This API Route requires two path parameters: the first one being the ID of the inventory item, and the second one being the ID of the location. In the body, you can optionally pass any of the location level’s attributes to update. In the example above, you update the `stocked_quantity` attribute of the location level. @@ -632,7 +632,7 @@ The request returns the inventory item associated with the location level as an ### Delete Location Level -You can delete a location level of an inventory item by sending a request to the [Delete Location Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitelocationlevelslocation): +You can delete a location level of an inventory item by sending a request to the [Delete Location Level API Route](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitelocationlevelslocation): @@ -696,7 +696,7 @@ curl -L -X DELETE '/admin/inventory-items//location-levels -This endpoint requires two path parameters: the first one being the inventory item’s ID and the second one being the location level’s ID. +This API Route requires two path parameters: the first one being the inventory item’s ID and the second one being the location level’s ID. The request returns the inventory item as an object. @@ -704,7 +704,7 @@ The request returns the inventory item as an object. ## Delete Inventory Item -You can delete an inventory item by sending a request to the [Delete Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitem): +You can delete an inventory item by sending a request to the [Delete Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitem): @@ -765,7 +765,7 @@ curl -L -X DELETE '/admin/inventory-items/' \ -This endpoint requires the inventory item’s ID be passed as a path parameter. +This API Route requires the inventory item’s ID be passed as a path parameter. It returns the following fields in the response: diff --git a/www/apps/docs/content/modules/multiwarehouse/admin/manage-item-allocations-in-orders.mdx b/www/apps/docs/content/modules/multiwarehouse/admin/manage-item-allocations-in-orders.mdx index 9783dd9aae..41ad35634d 100644 --- a/www/apps/docs/content/modules/multiwarehouse/admin/manage-item-allocations-in-orders.mdx +++ b/www/apps/docs/content/modules/multiwarehouse/admin/manage-item-allocations-in-orders.mdx @@ -70,13 +70,13 @@ You can learn more about [authenticating as an admin user in the API reference]( Using the reservations admin REST APIs, you can create an item allocation or reservation for any resource, and not just items in an order. This gives you more options in how you handle item allocations. -In this guide, however, the focus will be on how to use these endpoints for order-related functionalities. +In this guide, however, the focus will be on how to use these API Routes for order-related functionalities. ### Create Item Allocation Item allocations are created automatically for items that are associated with product variants having the `manage_inventory` attribute enabled. You typically don’t need to create an item allocation, unless you delete the previous item allocation. -You can create an item allocation by sending a request to the [Create a Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservations): +You can create an item allocation by sending a request to the [Create a Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservations): @@ -159,7 +159,7 @@ curl -L -X POST '/admin/reservations' \ -This endpoint requires the following body parameters: +This API Route requires the following body parameters: - `line_item_id`: The ID of the order’s line item the allocation is being created for. - `location_id`: The ID of the location the item is being allocated from. @@ -172,7 +172,7 @@ The request returns the created reservation as an object. When listing item allocations, by default, you’ll be retrieving all item allocations in your commerce system. You can, however, provide optional fields to filter the item allocations retrieved. -You can retrieve the item allocations of a line item in an order using the [List Reservations endpoint](https://docs.medusajs.com/api/admin#reservations_getreservations): +You can retrieve the item allocations of a line item in an order using the [List Reservations API Route](https://docs.medusajs.com/api/admin#reservations_getreservations): @@ -243,13 +243,13 @@ curl -L -X GET '/admin/reservations?line_item_id=' \ -This endpoint does not require any path or query parameters. As mentioned earlier, you can pass query parameters to filter the reservations. In the code snippets above, you filter the reservations by a line item ID. You can, however, filter by other attributes, such as the ID of the location. You can refer to the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a full list of query parameters. +This API Route doesn't require any path or query parameters. As mentioned earlier, you can pass query parameters to filter the reservations. In the code snippets above, you filter the reservations by a line item ID. You can, however, filter by other attributes, such as the ID of the location. You can refer to the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a full list of query parameters. The request returns the reservations along with [pagination fields](https://docs.medusajs.com/api/admin#pagination). ### Retrieve Item Allocation -You can retrieve a single item allocation by its ID using the [Get a Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_getreservationsreservation): +You can retrieve a single item allocation by its ID using the [Get a Reservation API Route](https://docs.medusajs.com/api/admin#reservations_getreservationsreservation): @@ -309,13 +309,13 @@ curl -L -X GET '/admin/reservations/' \ -This endpoint requires the reservation’s ID as a path parameter. +This API Route requires the reservation’s ID as a path parameter. The request returns the reservation as an object. ### Update Item Allocation -You can update an item allocation to change the location to allocate from or the quantity to allocate by sending a request to the [Update Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation): +You can update an item allocation to change the location to allocate from or the quantity to allocate by sending a request to the [Update Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation): @@ -388,7 +388,7 @@ curl -L -X POST '/admin/reservations/' \ -This endpoint requires the ID of the reservation as a path parameter. +This API Route requires the ID of the reservation as a path parameter. In the request body parameters, you can optionally pass any of the following parameters to make updates to the reservation: @@ -402,7 +402,7 @@ The request returns the updated reservation as an object. Deleting an item allocation means that the quantity that was previously reserved is no longer reserved. -You can delete an item allocation by sending a request to the [Delete Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation): +You can delete an item allocation by sending a request to the [Delete Reservation API Route](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation): @@ -461,12 +461,12 @@ curl -L -X DELETE '/admin/reservations/' \ -This endpoint requires the reservation ID to be passed as a path parameter. +This API Route requires the reservation ID to be passed as a path parameter. The request returns the following fields: - `id`: The ID of the reservation. -- `object`: The type of object that was removed. In this case, the value will be `reservation`. +- `object`: The type of object that was removed. In this case, the value will be `reservation`. - `deleted`: A boolean value indicating whether the reservation was successfully deleted. --- @@ -573,7 +573,7 @@ curl -L -X POST '/admin/orders//fulfillment' \ The `location_id` is an optional parameter that allows you to specify where to fulfill the item from. This subsequently decrements the stock quantity of the product variant in that location. -You can learn more about this endpoint’s parameters and response in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments). +You can learn more about this API Route's parameters and response in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments). --- @@ -679,7 +679,7 @@ curl -L -X POST '/admin/orders//return' \ The `location_id` is an optional parameter that allows you to specify where to return the item to. This subsequently increments the stock quantity of the product variant in that location. -You can learn more about this endpoint’s parameters and response in [the API reference](https://docs.medusajs.com/api/admin#orders_postordersorderreturns). +You can learn more about this API Route's parameters and response in [the API reference](https://docs.medusajs.com/api/admin#orders_postordersorderreturns). --- diff --git a/www/apps/docs/content/modules/multiwarehouse/admin/manage-reservations.mdx b/www/apps/docs/content/modules/multiwarehouse/admin/manage-reservations.mdx index f9a95e2b49..539622a55b 100644 --- a/www/apps/docs/content/modules/multiwarehouse/admin/manage-reservations.mdx +++ b/www/apps/docs/content/modules/multiwarehouse/admin/manage-reservations.mdx @@ -31,7 +31,7 @@ You want to add or use the following admin functionalities: :::note -You can check the [API reference](https://docs.medusajs.com/api/admin) for all available Reservations endpoints. +You can check the [API reference](https://docs.medusajs.com/api/admin) for all available Reservations API Routes. ::: @@ -69,7 +69,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Reservations -You can list all reservations in your store by sending a request to the [List Reservations endpoint](https://docs.medusajs.com/api/admin#reservations_getreservations): +You can list all reservations in your store by sending a request to the [List Reservations API Route](https://docs.medusajs.com/api/admin#reservations_getreservations): @@ -134,9 +134,9 @@ curl -L -X GET '/admin/reservations' \ -This endpoint does not require any query or path parameters. You can pass it query parameters for filtering or pagination purposes. Check out the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a list of accepted query parameters. +This API Route doesn't require any query or path parameters. You can pass it query parameters for filtering or pagination purposes. Check out the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a list of accepted query parameters. -This endpoint returns an array of reservations along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). +This API Route returns an array of reservations along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). --- @@ -148,7 +148,7 @@ Before you create a reservation for a product variant, make sure you’ve create ::: -You can create a reservation by sending a request to the [Create Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservations): +You can create a reservation by sending a request to the [Create Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservations): @@ -227,7 +227,7 @@ curl -L -X POST '/admin/reservations' \ -This endpoint requires the following body parameters: +This API Route requires the following body parameters: - `location_id`: The ID of the location the reservation is created in. - `inventory_item_id`: The ID of the inventory item the product variant is associated with. @@ -239,7 +239,7 @@ The request returns the created reservation as an object. ## Update a Reservation -You can update a reservation by sending a request to the [Update Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation): +You can update a reservation by sending a request to the [Update Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation): @@ -312,7 +312,7 @@ curl -L -X POST '/admin/reservations/' \ -This endpoint requires the ID of the reservation as a path parameter. +This API Route requires the ID of the reservation as a path parameter. In the request body parameters, you can optionally pass any of the following parameters to make updates to the reservation: @@ -326,7 +326,7 @@ The request returns the updated reservation as an object. ## Delete a Reservation -You can delete a reservation by sending a request to the [Delete Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation): +You can delete a reservation by sending a request to the [Delete Reservation API Route](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation): @@ -385,7 +385,7 @@ curl -L -X DELETE '/admin/reservations/' \ -This endpoint requires the reservation ID to be passed as a path parameter. +This API Route requires the reservation ID to be passed as a path parameter. The request returns the following fields: diff --git a/www/apps/docs/content/modules/multiwarehouse/admin/manage-stock-locations.mdx b/www/apps/docs/content/modules/multiwarehouse/admin/manage-stock-locations.mdx index 0125c44e54..f7f4bd2e39 100644 --- a/www/apps/docs/content/modules/multiwarehouse/admin/manage-stock-locations.mdx +++ b/www/apps/docs/content/modules/multiwarehouse/admin/manage-stock-locations.mdx @@ -59,7 +59,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Stock Locations -You can list stock locations by using the [List Stock Locations endpoint](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations): +You can list stock locations by using the [List Stock Locations API Route](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations): @@ -128,7 +128,7 @@ curl -L -X GET '/admin/stock-locations' \ -This endpoint does not require any path or query parameters. You can, however, pass it query parameters to search or filter the list of stock locations. For example, you can pass the `q` query parameter to search through the locations by name. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations). +This API Route doesn't require any path or query parameters. You can, however, pass it query parameters to search or filter the list of stock locations. For example, you can pass the `q` query parameter to search through the locations by name. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations). The request returns an array of stock location objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). @@ -136,7 +136,7 @@ The request returns an array of stock location objects along with [pagination pa ## Create a Stock Location -You can create a stock location using the [Create a Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations): +You can create a stock location using the [Create a Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations): @@ -207,7 +207,7 @@ curl -L -X POST '/admin/stock-locations' \ -This endpoint requires in its body parameters the `name` field, which is the name of the stock location. You can also pass in the request body parameters other fields related to the address or metadata. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations). +This API Route requires in its body parameters the `name` field, which is the name of the stock location. You can also pass in the request body parameters other fields related to the address or metadata. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations). This request returns the created stock location as an object. @@ -215,7 +215,7 @@ This request returns the created stock location as an object. ## Retrieve a Stock Location -You can retrieve a stock location by sending a request to the [Get Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation): +You can retrieve a stock location by sending a request to the [Get Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation): @@ -277,7 +277,7 @@ curl -L -X GET '/admin/stock-locations/' \ -This endpoint requires the stock location ID to be passed as a path parameter. It also accepts query parameters related to expanding and selecting fields. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation). +This API Route requires the stock location ID to be passed as a path parameter. It also accepts query parameters related to expanding and selecting fields. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation). It returns the stock location as an object. @@ -285,7 +285,7 @@ It returns the stock location as an object. ## Associate a Stock Location with a Sales Channel -You can associate a stock location with a sales channel by sending a request to the [Associate Stock Channel endpoint](https://docs.medusajs.com/api/admin#sales-channels_postsaleschannelssaleschannelstocklocation): +You can associate a stock location with a sales channel by sending a request to the [Associate Stock Channel API Route](https://docs.medusajs.com/api/admin#sales-channels_postsaleschannelssaleschannelstocklocation): @@ -357,7 +357,7 @@ curl -L -X POST '/admin/sales-channels//stock-locations -This endpoint requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re associating the sales channel with. +This API Route requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re associating the sales channel with. This request returns the sales channel object. @@ -371,7 +371,7 @@ You can associate a location with more than one sales channel, and you can assoc ## Remove Association Between Stock Location and Sales Channel -You can remove the association between a stock location and a sales channel by sending a request to the [Remove Stock Location Association endpoint](https://docs.medusajs.com/api/admin#sales-channels_deletesaleschannelssaleschannelstocklocation): +You can remove the association between a stock location and a sales channel by sending a request to the [Remove Stock Location Association API Route](https://docs.medusajs.com/api/admin#sales-channels_deletesaleschannelssaleschannelstocklocation): @@ -446,7 +446,7 @@ curl -L -X DELETE '/admin/sales-channels//stock-locatio -This endpoint requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re removing the association of the sales channel with. +This API Route requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re removing the association of the sales channel with. The request returns the following fields: @@ -464,7 +464,7 @@ This request does not delete the stock location. It only removes the association ## Update a Stock Location -You can update a stock location by sending a request to the [Update Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation): +You can update a stock location by sending a request to the [Update Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation): @@ -537,7 +537,7 @@ curl -L -X POST '/admin/stock-locations/' \ -This endpoint requires the ID of a stock location as a path parameter. In its body parameters, you can pass any of the location’s attributes to update, such as the name or address. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation). +This API Route requires the ID of a stock location as a path parameter. In its body parameters, you can pass any of the location’s attributes to update, such as the name or address. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation). This request returns the updated stock location as an object. @@ -545,7 +545,7 @@ This request returns the updated stock location as an object. ## Delete a Stock Location -You can delete a stock location by sending a request to the [Delete Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_deletestocklocationsstocklocation): +You can delete a stock location by sending a request to the [Delete Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_deletestocklocationsstocklocation): @@ -604,7 +604,7 @@ curl -L -X DELETE '/admin/stock-locations/' \ -This endpoint requires the ID of the stock location as a path parameter. +This API Route requires the ID of the stock location as a path parameter. It returns the following fields in the response: diff --git a/www/apps/docs/content/modules/multiwarehouse/backend/create-inventory-service.md b/www/apps/docs/content/modules/multiwarehouse/backend/create-inventory-service.md index 7876370907..198516a468 100644 --- a/www/apps/docs/content/modules/multiwarehouse/backend/create-inventory-service.md +++ b/www/apps/docs/content/modules/multiwarehouse/backend/create-inventory-service.md @@ -19,7 +19,7 @@ This guide will only explain what is required to create in your custom inventory :::note -It should be noted that the Medusa backend expects the inventory module to have entities for an inventory item, an inventory level, and a reservation item, as it uses the IDs of those entities when orchestrating between different modules and the in the endpoints it exposes. You can learn more about this in the [Inventory Module Architecture documentation](../inventory-module.md). +It should be noted that the Medusa backend expects the inventory module to have entities for an inventory item, an inventory level, and a reservation item, as it uses the IDs of those entities when orchestrating between different modules and the in the API Routes it exposes. You can learn more about this in the [Inventory Module Architecture documentation](../inventory-module.md). ::: diff --git a/www/apps/docs/content/modules/multiwarehouse/backend/create-stock-location-service.md b/www/apps/docs/content/modules/multiwarehouse/backend/create-stock-location-service.md index de7981c7f5..db260e3c7f 100644 --- a/www/apps/docs/content/modules/multiwarehouse/backend/create-stock-location-service.md +++ b/www/apps/docs/content/modules/multiwarehouse/backend/create-stock-location-service.md @@ -19,7 +19,7 @@ This guide will only explain what is required to create in your custom stock loc :::note -It should be noted that the Medusa backend expects the stock location module to have entities for a location and a location address, as it uses the IDs of those entities when orchestrating between different modules and the in the endpoints it exposes. You can learn more about this in the [Stock Location Module Architecture documentation](../stock-location-module.md). +It should be noted that the Medusa backend expects the stock location module to have entities for a location and a location address, as it uses the IDs of those entities when orchestrating between different modules and the in the API Routes it exposes. You can learn more about this in the [Stock Location Module Architecture documentation](../stock-location-module.md). ::: diff --git a/www/apps/docs/content/modules/orders/admin/edit-order.mdx b/www/apps/docs/content/modules/orders/admin/edit-order.mdx index af543269fe..d391fec35d 100644 --- a/www/apps/docs/content/modules/orders/admin/edit-order.mdx +++ b/www/apps/docs/content/modules/orders/admin/edit-order.mdx @@ -8,7 +8,7 @@ import TabItem from '@theme/TabItem'; # How to Edit an Order -In this document, you’ll learn how to create an order edit using the Admin API endpoints. +In this document, you’ll learn how to create an order edit using the Admin API Routes. ## Overview @@ -80,7 +80,7 @@ You must have an existing order that you want to edit. Before you can start making changes to an order, you have to create a new order edit. -To do that, send a request to the [Create an OrderEdit](https://docs.medusajs.com/api/admin#order-edits_postorderedits) endpoint: +To do that, send a request to the [Create an OrderEdit API Route](https://docs.medusajs.com/api/admin#order-edits_postorderedits): @@ -150,7 +150,7 @@ curl -L -X POST '/admin/order-edits' \ -This endpoint has one required request body parameter `order_id` which is the ID of the order this edit is being created for. +This API Route has one required request body parameter `order_id` which is the ID of the order this edit is being created for. This request returns the Order Edit under the `order_edit` property. @@ -174,7 +174,7 @@ You can only make changes to items that have not been fulfilled yet in the order ### Add an Item -To add a new item to the original order, send a request to the [Add Line Item](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitems) endpoint: +To add a new item to the original order, send a request to the [Add Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitems): @@ -259,7 +259,7 @@ This request returns the Order Edit object. You can access returned item changes You can edit an item’s quantity in the original order. -To update an item, send a request to the [Update Line Item](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitemslineitem) endpoint: +To update an item, send a request to the [Update Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitemslineitem): @@ -342,7 +342,7 @@ This request returns the Order Edit object. You can access returned item changes ### Remove an Item -You can remove an item from the original order by sending a request to the [Remove Line Item](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsordereditlineitemslineitem) endpoint: +You can remove an item from the original order by sending a request to the [Remove Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsordereditlineitemslineitem): @@ -413,7 +413,7 @@ This request returns the Order Edit object. You can access returned item changes A merchant might make a mistake while making a change to the original order’s items. Using the Admin API, you can revert item changes previously created. -To revert an item change, send a request to the [Delete Item Change](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsorderedititemchange) endpoint: +To revert an item change, send a request to the [Delete Item Change API Route](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsorderedititemchange): @@ -491,7 +491,7 @@ This request returns an object with the following properties: After an Order Edit is created and all the item changes are added, it must be moved into the request state. -To move an Order Edit into the request state, send a request to the [Request Confirmation](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditrequest) endpoint: +To move an Order Edit into the request state, send a request to the [Request Confirmation API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditrequest): @@ -587,7 +587,7 @@ When the merchant force-confirms the order edit, however, it bypasses the paymen This section covers how the Admin API can be used to force-confirm the Order Edit. You can refer to [this documentation to learn how to implement Order Edit confirmation on the storefront](../storefront/handle-order-edits.mdx). -To confirm an Order Edit, send a request to the [Confirm Order Edit](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditconfirm) endpoint: +To confirm an Order Edit, send a request to the [Confirm Order Edit API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditconfirm): @@ -670,7 +670,7 @@ You can learn how to allow customers to authorize payment on the storefront in [ ### Capture Payment -If the payment is authorized by the customer, it can be captured by sending a request to the [Capture Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture) endpoint: +If the payment is authorized by the customer, it can be captured by sending a request to the [Capture Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture): @@ -736,7 +736,7 @@ It returns in the response the full Payment object. When the total after the order edit is less than the original order total, the merchant can refund the difference to the customer. -To refund the difference to the customer, send a request to the [Refund Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds) endpoint: +To refund the difference to the customer, send a request to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds): diff --git a/www/apps/docs/content/modules/orders/admin/manage-claims.mdx b/www/apps/docs/content/modules/orders/admin/manage-claims.mdx index ad4e2db205..6b7bc694d0 100644 --- a/www/apps/docs/content/modules/orders/admin/manage-claims.mdx +++ b/www/apps/docs/content/modules/orders/admin/manage-claims.mdx @@ -58,7 +58,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## View Order’s Claims -To view an order’s claims, you can retrieve the order using the [Get Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder) and access the order’s claims: +To view an order’s claims, you can retrieve the order using the [Get Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder) and access the order’s claims: @@ -137,7 +137,7 @@ The request returns the order as an object. In that object, you can access an ar ## Create Claim -You can create a claim by sending a request to the [Create Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaims): +You can create a claim by sending a request to the [Create Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaims): @@ -232,7 +232,7 @@ curl -L -X POST '/admin/orders//claims' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. In the request body, the following parameters are required: @@ -255,7 +255,7 @@ The request returns the updated order as an object. You can access the order’s ## Update a Claim -You can update a claim by sending a request to the [Update Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaim): +You can update a claim by sending a request to the [Update Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaim): @@ -330,7 +330,7 @@ curl -L -X POST '/admin/orders//claims/' \ -This endpoint requires the ID of the order and the claim to be passed as path parameters. +This API Route requires the ID of the order and the claim to be passed as path parameters. In the request body, you can pass any of the claim’s fields that you want to update as parameters. In the example above, the `no_notification` field is updated. @@ -346,7 +346,7 @@ Fulfillments are available on a claim object under the `fulfillments` property, ### Create Fulfillment -You can create a fulfillment for a claim by sending a request to the [Create Claim Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments): +You can create a fulfillment for a claim by sending a request to the [Create Claim Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments): @@ -408,7 +408,7 @@ curl -L -X POST '/admin/orders//claims//fulfill -This endpoint requires the order and claim IDs as path parameters. +This API Route requires the order and claim IDs as path parameters. In the request body, you can pass optional parameters such as `metadata` or `no_notification`. These parameters will be used to create the fulfillment. You can learn more about available request body parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments). @@ -416,7 +416,7 @@ The request returns the updated order as an object. You can access the order’s ### Create a Shipment -You can create a shipment for a claim by sending a request to the [Create Claim Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments): +You can create a shipment for a claim by sending a request to the [Create Claim Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments): @@ -490,7 +490,7 @@ curl -L -X POST '/admin/orders//claims//shipmen -This endpoint requires the order and claim IDs as path parameters. +This API Route requires the order and claim IDs as path parameters. In the request body, it’s required to pass the `fulfillment_id` parameter, which is the ID of the fulfillment the shipment is being created for. You can pass other optional parameters, such as an array of tracking numbers. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments). @@ -508,7 +508,7 @@ You can’t cancel a fulfillment that has a shipment ::: -You can cancel a fulfillment by sending a request to the [Cancel Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersclaimfulfillmentscancel): +You can cancel a fulfillment by sending a request to the [Cancel Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersclaimfulfillmentscancel): @@ -576,7 +576,7 @@ curl -L -X POST '/admin/orders//claims//fulfill -This endpoint requires the order, claim, and fulfillment IDs to be passed as path parameters. +This API Route requires the order, claim, and fulfillment IDs to be passed as path parameters. The request returns the updated order as an object. You can access the claims using the `claims` property of the order object, which is an array of claim objects. @@ -592,7 +592,7 @@ You can’t cancel a claim that has been refunded. You must also cancel the clai ::: -You can cancel a claim by sending a request to the [Cancel Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel): +You can cancel a claim by sending a request to the [Cancel Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel): @@ -651,7 +651,7 @@ curl -L -X POST '/admin/orders//claims//cancel' -This endpoint requires the order and claim IDs as path parameters. +This API Route requires the order and claim IDs as path parameters. The request returns the updated order as an object. You can access the claims using the `claims` property of the order object, which is an array of claim objects. diff --git a/www/apps/docs/content/modules/orders/admin/manage-draft-orders.mdx b/www/apps/docs/content/modules/orders/admin/manage-draft-orders.mdx index 4432f0b1c2..565a08f40e 100644 --- a/www/apps/docs/content/modules/orders/admin/manage-draft-orders.mdx +++ b/www/apps/docs/content/modules/orders/admin/manage-draft-orders.mdx @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Draft Orders -You can list draft orders by sending a request to the [List Draft Orders endpoint](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders): +You can list draft orders by sending a request to the [List Draft Orders API Route](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders): @@ -117,7 +117,7 @@ curl -L -X GET '/admin/draft-orders' \ -This endpoint does not require any path or query parameters. You can pass search or pagination query parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders). +This API Route doesn't require any path or query parameters. You can pass search or pagination query parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders). The request returns an array of draft order objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). @@ -125,7 +125,7 @@ The request returns an array of draft order objects along with [pagination param ## Create a Draft Order -You can create a draft order by sending a request to the [Create Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders): +You can create a draft order by sending a request to the [Create Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders): @@ -277,7 +277,7 @@ curl -L -X POST '/admin/draft-orders' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `email`: a string indicating the email of the customer to associate this draft order with. - `region_id`: a string indicating the ID of the region this draft order belongs to. @@ -298,7 +298,7 @@ The request returns the created draft order as an object. ## Retrieve Draft Order -You can retrieve a draft order by sending a request to the [Get Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_getdraftordersdraftorder): +You can retrieve a draft order by sending a request to the [Get Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_getdraftordersdraftorder): @@ -358,7 +358,7 @@ curl -L -X GET '/admin/draft-orders/' \ -This endpoint requires the draft order’s ID as a path parameter. +This API Route requires the draft order’s ID as a path parameter. The request returns the draft order as an object. @@ -366,7 +366,7 @@ The request returns the draft order as an object. ## Update Draft Order -You can update a draft order by sending a request to the [Update Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder): +You can update a draft order by sending a request to the [Update Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder): @@ -439,7 +439,7 @@ curl -L -X POST '/admin/draft-orders/' \ -This endpoint requires the draft order’s ID as a path parameter. +This API Route requires the draft order’s ID as a path parameter. In the request body, you can pass any of the draft order’s fields to update. In the example above, you update the `email` field. Check out the [API reference](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder) to learn about other accepted request body parameters. @@ -451,7 +451,7 @@ The request returns the updated draft order as an object. ### Add Line Items -You can add line items to a draft order by sending a request to the [Create Line Items endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitems): +You can add line items to a draft order by sending a request to the [Create Line Items API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitems): @@ -526,7 +526,7 @@ curl -L -X POST '/admin/draft-orders//line-items' \ -This endpoint requires the ID of the draft order as a path parameter. +This API Route requires the ID of the draft order as a path parameter. In the request body, it’s required to pass the `quantity` parameter, which is a number indicating the quantity of the item in the draft order. You can also pass other optional parameters based on the type of line item you’re adding. @@ -541,7 +541,7 @@ The request returns the updated draft order as an object. You can access the dra ### Update Line Item -You can update a line item by sending a request to the [Update Line Item endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem): +You can update a line item by sending a request to the [Update Line Item API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem): @@ -617,7 +617,7 @@ curl -L -X POST '/admin/draft-orders//line-items/ -This endpoint requires the draft order and line item’s IDs as path parameters. +This API Route requires the draft order and line item’s IDs as path parameters. In the request body, you can pass any of the line item’s fields as parameters to update them. In the example above, you pass the `quantity` parameter to update the quantity of the item. Check out the [API reference](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem) for a full list of request body parameters. @@ -625,7 +625,7 @@ The request returns the updated draft order as an object. You can access the dra ### Delete Line Item -You can delete a line item by sending a request to the [Delete Line Item endpoint](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorderlineitemsitem): +You can delete a line item by sending a request to the [Delete Line Item API Route](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorderlineitemsitem): @@ -686,7 +686,7 @@ curl -L -X DELETE '/admin/draft-orders//line-items/ -This endpoint requires the draft order and line item’s IDs as path parameters. +This API Route requires the draft order and line item’s IDs as path parameters. The request returns the updated draft order as an object. You can access the draft order’s items by accessing the `carts` property in the draft item, then the `items` property. The `items` property is an array of line item objects. @@ -696,7 +696,7 @@ The request returns the updated draft order as an object. You can access the dra Registering the draft order’s payment leads to authorizing and capturing the payment using the `system` payment method. This would complete the draft order and create an order from it. -You can register the draft order payment by sending a request to the [Register Draft Order Payment endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment): +You can register the draft order payment by sending a request to the [Register Draft Order Payment API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment): @@ -755,7 +755,7 @@ curl -L -X POST '/admin/draft-orders//pay' \ -This endpoint requires the draft order’s ID as a path parameter. +This API Route requires the draft order’s ID as a path parameter. The request returns the order created from the draft order as an object. @@ -763,7 +763,7 @@ The request returns the order created from the draft order as an object. ## Delete a Draft Order -You can delete a draft order by sending a request to the [Delete Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorder): +You can delete a draft order by sending a request to the [Delete Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorder): @@ -822,7 +822,7 @@ curl -L -X DELETE '/admin/draft-orders/' \ -This endpoint requires the draft order’s ID as a path parameter. +This API Route requires the draft order’s ID as a path parameter. The request returns the following fields: diff --git a/www/apps/docs/content/modules/orders/admin/manage-orders.mdx b/www/apps/docs/content/modules/orders/admin/manage-orders.mdx index d225cbf56c..1199569cf3 100644 --- a/www/apps/docs/content/modules/orders/admin/manage-orders.mdx +++ b/www/apps/docs/content/modules/orders/admin/manage-orders.mdx @@ -60,7 +60,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Orders -You can list orders by sending a request to the [List Orders endpoint](https://docs.medusajs.com/api/admin#orders_getorders): +You can list orders by sending a request to the [List Orders API Route](https://docs.medusajs.com/api/admin#orders_getorders): @@ -123,13 +123,13 @@ curl -L -X GET '/admin/orders' \ -This endpoint does not require any path parameters. You can pass it query parameters to filter the orders received. +This API Route doesn't require any path parameters. You can pass it query parameters to filter the orders received. The request returns an array of orders along with [pagination fields](https://docs.medusajs.com/api/admin#pagination). ### Filter Orders -This endpoint accepts a variety of query parameters that allow you to filter orders. You can check available query parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_getorders). +This API Route accepts a variety of query parameters that allow you to filter orders. You can check available query parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_getorders). For example, you can filter the orders by one or more status: @@ -380,7 +380,7 @@ curl -L -X GET '/admin/orders?status[]=completed&sales_channel_id[] ## Retrieve an Order -You can retrieve an order by sending a request to the [Get an Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder): +You can retrieve an order by sending a request to the [Get an Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder): @@ -440,7 +440,7 @@ curl -L -X GET '/admin/orders/' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. The request returns the full order as an object. @@ -461,7 +461,7 @@ Updating an order’s details can include updating its: - Shipping Method - `no_notification` property -You can update any of the above details of an order by sending a request to the [Update an Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersorder): +You can update any of the above details of an order by sending a request to the [Update an Order API Route](https://docs.medusajs.com/api/admin#orders_postordersorder): @@ -534,7 +534,7 @@ curl -L -X POST '/admin/orders/' \ -This endpoint requires the order’s ID to be passed as a path parameter. +This API Route requires the order’s ID to be passed as a path parameter. In the request body parameters, you can pass any of the order’s fields mentioned earlier that you want to update. In the example above, you edit the email associated with the order. You can learn about other available request body parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorder). @@ -546,7 +546,7 @@ The request returns the updated order as an object. ### Capture an Order’s Payment -You can capture an order’s payment by sending a request to the [Capture Order’s Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercapture): +You can capture an order’s payment by sending a request to the [Capture Order’s Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersordercapture): @@ -606,7 +606,7 @@ curl -L -X POST '/admin/orders//capture' \ -This endpoint requires the Order ID as a path parameter. +This API Route requires the Order ID as a path parameter. The request returns the updated order as an object. @@ -614,7 +614,7 @@ The request returns the updated order as an object. You can refund an amount that is less than `order.refundable_amount`. -To refund payment, send a request to the [Refund Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderrefunds): +To refund payment, send a request to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderrefunds): @@ -691,7 +691,7 @@ curl -L -X POST '/admin/orders//refund' \ -This endpoint requires the order’s ID to be passed as a path parameter. +This API Route requires the order’s ID to be passed as a path parameter. The following parameters are required in the request body parameters: @@ -708,7 +708,7 @@ The request returns the updated order as an object. ### Create a Fulfillment -You can create a fulfillment by sending a request to the [Create a Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments): +You can create a fulfillment by sending a request to the [Create a Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments): @@ -801,7 +801,7 @@ curl -L -X POST '/admin/orders//fulfillment' \ -This endpoint requires the order’s ID to be passed as a path parameter. +This API Route requires the order’s ID to be passed as a path parameter. In the request body, the `items` parameter is required. It’s an array of objects that are the items to fulfill. You can fulfill all items in the order or some items. @@ -816,7 +816,7 @@ The request returns the updated order as an object. ### Create Shipment -You can create a shipment for a fulfillment by sending a request to the [Create Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersordershipment): +You can create a shipment for a fulfillment by sending a request to the [Create Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersordershipment): @@ -889,7 +889,7 @@ curl -L -X POST '/admin/orders//shipment' \ -This endpoint requires passing the order’s ID as a path parameter. +This API Route requires passing the order’s ID as a path parameter. In the request body, the `fulfillment_id` parameter is required. Its value is the ID of the fulfillment to create the shipment for. You can also pass other optional body parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersordershipment). @@ -897,7 +897,7 @@ The request returns the updated order as an object. ### Cancel Fulfillment -You can cancel a fulfillment by sending a request to the [Cancel Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillmentscancel): +You can cancel a fulfillment by sending a request to the [Cancel Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillmentscancel): @@ -958,7 +958,7 @@ curl -L -X POST '/admin/orders//fulfillments//can -This endpoint requires passing the order’s ID and fulfillment ID as path parameters. +This API Route requires passing the order’s ID and fulfillment ID as path parameters. The request returns the updated order as an object. @@ -966,7 +966,7 @@ The request returns the updated order as an object. ## Completing an Order -You can mark an order completed, changing its status, by sending a request to the [Complete an Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercomplete): +You can mark an order completed, changing its status, by sending a request to the [Complete an Order API Route](https://docs.medusajs.com/api/admin#orders_postordersordercomplete): @@ -1025,7 +1025,7 @@ curl -L -X POST '/admin/orders//complete' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. The request returns the updated order as an object. @@ -1033,7 +1033,7 @@ The request returns the updated order as an object. ## Cancel an Order -You can cancel an order by sending a request to the [Cancel Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercancel): +You can cancel an order by sending a request to the [Cancel Order API Route](https://docs.medusajs.com/api/admin#orders_postordersordercancel): @@ -1092,7 +1092,7 @@ curl -L -X POST '/admin/orders//cancel' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. The request returns the updated order as an object. @@ -1100,7 +1100,7 @@ The request returns the updated order as an object. ## Archive Order -You can archive an order by sending a request to the [Archive Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderarchive): +You can archive an order by sending a request to the [Archive Order API Route](https://docs.medusajs.com/api/admin#orders_postordersorderarchive): @@ -1159,7 +1159,7 @@ curl -L -X POST '/admin/orders//archive' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. The request returns the updated order as an object. diff --git a/www/apps/docs/content/modules/orders/admin/manage-returns.mdx b/www/apps/docs/content/modules/orders/admin/manage-returns.mdx index d3ecac197a..75b88b01c7 100644 --- a/www/apps/docs/content/modules/orders/admin/manage-returns.mdx +++ b/www/apps/docs/content/modules/orders/admin/manage-returns.mdx @@ -57,7 +57,7 @@ Return reasons allow you to specify why an item is returned. They are especially ### List Return Reasons -You can list available return reasons using the [List Return Reasons endpoint](https://docs.medusajs.com/api/admin#return-reasons_getreturnreasons): +You can list available return reasons using the [List Return Reasons API Route](https://docs.medusajs.com/api/admin#return-reasons_getreturnreasons): @@ -124,13 +124,13 @@ curl -L -X GET '/admin/return-reasons' \ -This endpoint does not require or accept any path or query parameters. +This API Route doesn't require or accept any path or query parameters. The request returns an array of return reason objects. ### Create a Return Reason -You can create a return reason using the [Create Return Reason endpoint](https://docs.medusajs.com/api/admin#return-reasons_postreturnreasons): +You can create a return reason using the [Create Return Reason API Route](https://docs.medusajs.com/api/admin#return-reasons_postreturnreasons): @@ -205,7 +205,7 @@ curl -L -X POST '/admin/return-reasons' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `label`: a string that will be used as the label of the return reason. This is typically the label shown to the customer or the merchant. - `value`: a string that is unique among return reasons. It is typically used internally for identification @@ -216,7 +216,7 @@ This request returns the created return reason as an object. ### Update a Return Reason -You can update a return reason by sending a request to the [Update Return Reason endpoint](https://docs.medusajs.com/api/admin#return-reasons_postreturnreasonsreason): +You can update a return reason by sending a request to the [Update Return Reason API Route](https://docs.medusajs.com/api/admin#return-reasons_postreturnreasonsreason): @@ -289,7 +289,7 @@ curl -L -X POST '/admin/return-reasons/' \ -This endpoint requires the return reason ID to be passed as a path parameter. +This API Route requires the return reason ID to be passed as a path parameter. In the request body, you can pass any of the return reason’s fields that you want to update as parameters. In the example above, the label is passed in the request body to be updated. @@ -297,7 +297,7 @@ The request returns the updated return reason as an object. ### Delete a Return Reason -You can delete a return reason by sending a request to the [Delete Return Reason endpoint](https://docs.medusajs.com/api/admin#return-reasons_deletereturnreason): +You can delete a return reason by sending a request to the [Delete Return Reason API Route](https://docs.medusajs.com/api/admin#return-reasons_deletereturnreason): @@ -356,7 +356,7 @@ curl -L -X DELETE '/admin/return-reasons/' \ -This endpoint requires the return reason ID as a path parameter. +This API Route requires the return reason ID as a path parameter. The request returns the following fields: @@ -370,11 +370,11 @@ The request returns the following fields: :::note -You can view all returns in your commerce system, regardless of which order they belong to, using the [List Returns endpoint](https://docs.medusajs.com/api/admin#return-reasons_getreturnreasons). +You can view all returns in your commerce system, regardless of which order they belong to, using the [List Returns API Route](https://docs.medusajs.com/api/admin#return-reasons_getreturnreasons). ::: -When you retrieve an order using the [Get Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder), you can access the returns within the order object: +When you retrieve an order using the [Get Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder), you can access the returns within the order object: @@ -445,7 +445,7 @@ curl -L -X GET '/admin/orders/' \ -This endpoint requires the order ID as a path parameter. +This API Route requires the order ID as a path parameter. The request returns the order as an object. In that object, you can access an array of return objects using the property `returns` of the order object. @@ -453,7 +453,7 @@ The request returns the order as an object. In that object, you can access an ar ## View a Swap’s Return -You can retrieve a swap either using the Get Order endpoint as explained [here](./manage-swaps.mdx#view-orders-swaps), or using the [List Swaps](https://docs.medusajs.com/api/admin#swaps_getswaps) or [Get Swap endpoint](https://docs.medusajs.com/api/admin#swaps_getswapsswap). +You can retrieve a swap either using the Get Order API Route as explained [here](./manage-swaps.mdx#view-orders-swaps), or using the [List Swaps](https://docs.medusajs.com/api/admin#swaps_getswaps) or [Get Swap](https://docs.medusajs.com/api/admin#swaps_getswapsswap) API Routes. In a swap object, the swap’s return is available under the `return_order` property. @@ -461,13 +461,13 @@ In a swap object, the swap’s return is available under the `return_order` prop ## View a Claim’s Return -You can retrieve a claim using the Get Order endpoint as explained [here](./manage-claims#view-orders-claims). In a claim object, the claim’s return is available under the `return_order` property. +You can retrieve a claim using the Get Order API Route as explained [here](./manage-claims#view-orders-claims). In a claim object, the claim’s return is available under the `return_order` property. --- ## Mark a Return as Received -You can mark a return as received by sending a request to the [Receive a Return endpoint](https://docs.medusajs.com/api/admin#returns_postreturnsreturnreceive): +You can mark a return as received by sending a request to the [Receive a Return API Route](https://docs.medusajs.com/api/admin#returns_postreturnsreturnreceive): @@ -555,7 +555,7 @@ curl -L -X POST '/admin/returns//receive' \ -This endpoint requires the ID of the return as a path parameter. +This API Route requires the ID of the return as a path parameter. In the request body, the `items` parameter is required. It’s an array of objects having the following properties: @@ -576,7 +576,7 @@ A received return can’t be canceled. ::: -You can cancel a return by sending a request to the [Cancel Return endpoint](https://docs.medusajs.com/api/admin#returns_postreturnsreturncancel): +You can cancel a return by sending a request to the [Cancel Return API Route](https://docs.medusajs.com/api/admin#returns_postreturnsreturncancel): @@ -635,7 +635,7 @@ curl -L -X POST '/admin/returns//cancel' \ -This endpoint requires the return ID to be passed as a path parameter. +This API Route requires the return ID to be passed as a path parameter. The request returns one of the following object types: diff --git a/www/apps/docs/content/modules/orders/admin/manage-swaps.mdx b/www/apps/docs/content/modules/orders/admin/manage-swaps.mdx index 0960cacd98..516d647b59 100644 --- a/www/apps/docs/content/modules/orders/admin/manage-swaps.mdx +++ b/www/apps/docs/content/modules/orders/admin/manage-swaps.mdx @@ -61,11 +61,11 @@ You can learn more about [authenticating as an admin user in the API reference]( :::note -If you want to view all swaps in your system, and not swaps specific to an order, you can use the [List Swaps endpoint](https://docs.medusajs.com/api/admin#swaps_getswaps) instead. +If you want to view all swaps in your system, and not swaps specific to an order, you can use the [List Swaps API Route](https://docs.medusajs.com/api/admin#swaps_getswaps) instead. ::: -You can view an order’s swaps by retrieving the order using the [Get Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder): +You can view an order’s swaps by retrieving the order using the [Get Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder): @@ -135,7 +135,7 @@ curl -L -X GET '/admin/orders/' \ -This endpoint requires the order ID to be passed as a path parameter. +This API Route requires the order ID to be passed as a path parameter. The request returns the order as an object. The order’s swaps are available under the `swaps` property, which is an array of swap objects. @@ -145,7 +145,7 @@ The request returns the order as an object. The order’s swaps are available un Processing a swap’s payment can mean either refunding or capturing payment, depending on the value of `difference_due` of the swap. If the `difference_due` is less than 0, then the payment should be refunded. If it’s greater than 0, then the payment should be captured. If it’s 0, no payment processing is performed. -Regardless of whether you need to refund or capture the payment, you can process the swap’s payment by sending a request to the [Process Swap Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapprocesspayment): +Regardless of whether you need to refund or capture the payment, you can process the swap’s payment by sending a request to the [Process Swap Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapprocesspayment): @@ -206,7 +206,7 @@ curl -L -X POST '/admin/orders//swaps//process-p -This endpoint requires the order ID and the swap ID as path parameters. +This API Route requires the order ID and the swap ID as path parameters. The request returns the updated order as an object. You can access the swaps of the order in the `order.swaps` property. It’s an array of swap objects. @@ -220,7 +220,7 @@ Fulfillments are available on a swap object under the `fulfillments` property, w ### Create a Fulfillment -You can create a fulfillment for a swap by sending a request to the [Create Swap Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapfulfillments): +You can create a fulfillment for a swap by sending a request to the [Create Swap Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapfulfillments): @@ -284,7 +284,7 @@ curl -L -X POST '/admin/orders//swaps//fulfillme -This endpoint requires the order ID and swap ID as path parameters. +This API Route requires the order ID and swap ID as path parameters. In the request body, you can pass optional parameters such as `metadata` or `no_notification`. These parameters will be used to create the fulfillment. You can learn more about available request body parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapfulfillments). @@ -292,7 +292,7 @@ The request returns the updated order as an object. You can access the order’s ### Create a Shipment -You can create a shipment for a swap’s fulfillment using the [Create Swap Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapshipments): +You can create a shipment for a swap’s fulfillment using the [Create Swap Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapshipments): @@ -368,7 +368,7 @@ curl -L -X POST '/admin/orders//swaps//shipments -This endpoint expects the order and swap IDs to be passed as path parameters. +This API Route expects the order and swap IDs to be passed as path parameters. In the request body, it’s required to pass the `fulfillment_id` parameter, which is the ID of the fulfillment the shipment is being created for. You can pass other optional parameters, such as an array of tracking numbers. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#tag/Orders/operation/PostOrdersOrderSwapsSwapShipments). @@ -386,7 +386,7 @@ You can’t cancel a fulfillment that has a shipment ::: -You can cancel a fulfillment by sending a request to the [Cancel Swap Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersswapfulfillmentscancel): +You can cancel a fulfillment by sending a request to the [Cancel Swap Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersswapfulfillmentscancel): @@ -454,7 +454,7 @@ curl -L -X POST '/admin/orders//swaps//fulfillme -This endpoint requires the order, swap, and fulfillment IDs to be passed as path parameters. +This API Route requires the order, swap, and fulfillment IDs to be passed as path parameters. The request returns the updated order as an object. You can access the swaps using the `swaps` property of the order object, which is an array of swap objects. @@ -470,7 +470,7 @@ You can’t cancel a swap that has been refunded. You must also cancel all swap ::: -You can cancel a swap by sending a request to the [Cancel Swap endpoint](https://docs.medusajs.com/api/admin#orders_postordersswapcancel): +You can cancel a swap by sending a request to the [Cancel Swap API Route](https://docs.medusajs.com/api/admin#orders_postordersswapcancel): @@ -531,7 +531,7 @@ curl -L -X POST '/admin/orders//swaps//cancel' \ -This endpoint requires the order and swap IDs as path parameters. +This API Route requires the order and swap IDs as path parameters. The request returns the updated order as an object. You can access the swaps using the `swaps` property of the order object, which is an array of swap objects. diff --git a/www/apps/docs/content/modules/orders/claims.md b/www/apps/docs/content/modules/orders/claims.md index f18af3da11..ca60ad9783 100644 --- a/www/apps/docs/content/modules/orders/claims.md +++ b/www/apps/docs/content/modules/orders/claims.md @@ -32,19 +32,19 @@ There are other important attributes discussed in later sections. Check out the Claims are created in Medusa by an admin (typically a merchant). They are created on an order, and depending on the claim’s type the admin can specify details like the amount to be refunded, or the items to be returned and the new items to replace them. -You can create a claim either using the [Create Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaims) or using the `ClaimService`'s [create method](../../references/services/classes/ClaimService.md#create). This section explains the process within the Create Claim endpoint, with a focus on the `create` method. +You can create a claim either using the [Create Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaims) or using the `ClaimService`'s [create method](../../references/services/classes/ClaimService.md#create). This section explains the process within the Create Claim API Route, with a focus on the `create` method. ### Idempotency Key -An Idempotency Key is a unique key associated with a claim. It is generated when the claim creation process is started by the admin using the [Create Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaims) and can be used to retry the claim creation safely if an error occurs. The idempotency key is stored in the `ClaimOrder` entity in the attribute `idempotency_key`. +An Idempotency Key is a unique key associated with a claim. It is generated when the claim creation process is started by the admin using the [Create Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaims) and can be used to retry the claim creation safely if an error occurs. The idempotency key is stored in the `ClaimOrder` entity in the attribute `idempotency_key`. You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx). -### Create Claim Endpoint Process +### Create Claim API Route Process -The following flow is implemented within the Create Claim endpoint: +The following flow is implemented within the Create Claim API Route: -![Create Claim Endpoint Overview](https://res.cloudinary.com/dza7lstvk/image/upload/v1682519207/Medusa%20Docs/Diagrams/create-claim-overview_iqek1f.jpg) +![Create Claim API Route Overview](https://res.cloudinary.com/dza7lstvk/image/upload/v1682519207/Medusa%20Docs/Diagrams/create-claim-overview_iqek1f.jpg) 1. When the idempotency key’s recovery point is `started`, the creation of the claim is started using the `ClaimService`'s [create method](../../references/services/classes/ClaimService.md#create). If the claim is created successfully, the idempotency key’s recovery point is changed to `claim_created`. In the `create` method: 1. If the type of the claim is `refund` and no refund amount is set, the refund amount is calculated based on the items in the claim using the `ClaimService`'s [getRefundTotalForClaimLinesOnOrder method](../../references/services/classes/ClaimService.md#getrefundtotalforclaimlinesonorder). @@ -63,19 +63,19 @@ The following flow is implemented within the Create Claim endpoint: If a claim’s type is `replace`, an admin can create a [fulfillment](./fulfillments.md) for the additional items that should be sent to the customer. -A fulfillment can be created either using the [Create Claim Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments) or the `ClaimService`'s [createFulfillment method](../../references/services/classes/ClaimService.md#createfulfillment). +A fulfillment can be created either using the [Create Claim Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments) or the `ClaimService`'s [createFulfillment method](../../references/services/classes/ClaimService.md#createfulfillment). :::note -The endpoint handles updating the inventory and reservations. So, if you choose to use the `createFulfillment` method, you should implement that within your code. +The API Route handles updating the inventory and reservations. So, if you choose to use the `createFulfillment` method, you should implement that within your code. ::: By default, when a fulfillment is created, the claim’s `fulfillment_status` is set to `fulfilled`. However, if any of the item’s quantity isn’t fulfilled successfully, the `fulfillment_status` is set to `requires_action`. -After creating a fulfillment, you can create a shipment for the fulfillment either using the [Create Claim Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments) or the `ClaimService`'s [createShipment method](../../references/services/classes/ClaimService.md#createshipment). If only some of the items and their quantities are shipped, the `fulfillment_status` of the claim is set to `partially_shipped`. Otherwise, if all items and quantities are shipped, the `fulfillment_status` of the claim is set to `shipped`. +After creating a fulfillment, you can create a shipment for the fulfillment either using the [Create Claim Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments) or the `ClaimService`'s [createShipment method](../../references/services/classes/ClaimService.md#createshipment). If only some of the items and their quantities are shipped, the `fulfillment_status` of the claim is set to `partially_shipped`. Otherwise, if all items and quantities are shipped, the `fulfillment_status` of the claim is set to `shipped`. -You can alternatively cancel a fulfillment either using the [Cancel Claim Fulfillment endpoint](https://docs.medusajs.com/api/admin#tag/Orders/operation/PostOrdersClaimFulfillmentsCancel) or the `ClaimService`'s [cancelFulfillment method](../../references/services/classes/ClaimService.md#cancelfulfillment). This would change the `fulfillment_status` of the claim to `canceled`. +You can alternatively cancel a fulfillment either using the [Cancel Claim Fulfillment API Route](https://docs.medusajs.com/api/admin#tag/Orders/operation/PostOrdersClaimFulfillmentsCancel) or the `ClaimService`'s [cancelFulfillment method](../../references/services/classes/ClaimService.md#cancelfulfillment). This would change the `fulfillment_status` of the claim to `canceled`. --- @@ -87,7 +87,7 @@ A claim's return can be marked as received, which would adjust the inventory and ## Cancel a Claim -An admin can cancel a claim if it hasn’t been refunded either using the [Cancel Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel) or the `ClaimService`'s [cancel method](../../references/services/classes/ClaimService.md#cancel). +An admin can cancel a claim if it hasn’t been refunded either using the [Cancel Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel) or the `ClaimService`'s [cancel method](../../references/services/classes/ClaimService.md#cancel). If any fulfillments were created, they must be canceled first. Similarly, if the claim is associated with a return, the return must be canceled first. diff --git a/www/apps/docs/content/modules/orders/draft-orders.md b/www/apps/docs/content/modules/orders/draft-orders.md index 4f6289087e..c6a32c728c 100644 --- a/www/apps/docs/content/modules/orders/draft-orders.md +++ b/www/apps/docs/content/modules/orders/draft-orders.md @@ -32,7 +32,7 @@ There are other important attributes discussed in later sections. Check out the ## How Draft Orders Work -You have full freedom in how you choose to implement creating draft orders. This section explains how it’s created in the Medusa backend using the [Create Draft Order](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders) and [Register Payment](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment) endpoints. +You have full freedom in how you choose to implement creating draft orders. This section explains how it’s created in the Medusa backend using the [Create Draft Order](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders) and [Register Payment](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment) API Routes. A draft order is created using the `DraftOrderService`'s [create method](../../references/services/classes/DraftOrderService.md#create). Within that method, a cart is created along with it. The cart is used to store the order’s details, such as the draft order’s items, shipping options, and more. The cart has the type `draft_order`. @@ -42,7 +42,7 @@ The payment must be authorized before the cart can be completed, which can be do :::note -In the Register Payment endpoint, the `system` payment method is used by default as the payment session of the cart. This means that the authorization and capturing of the payment don’t actually trigger any processes with existing payment processors integrated into your Medusa backend. It’s expected that the merchant will handle these processes manually. +In the Register Payment API Route, the `system` payment method is used by default as the payment session of the cart. This means that the authorization and capturing of the payment don’t actually trigger any processes with existing payment processors integrated into your Medusa backend. It’s expected that the merchant will handle these processes manually. ::: diff --git a/www/apps/docs/content/modules/orders/orders.md b/www/apps/docs/content/modules/orders/orders.md index 45af87fe1f..03970119d6 100644 --- a/www/apps/docs/content/modules/orders/orders.md +++ b/www/apps/docs/content/modules/orders/orders.md @@ -182,7 +182,7 @@ Medusa provides the necessary infrastructure and tooling that allows automating The Medusa backend facilitates automating these flows by allowing the customer to submit a [return](https://docs.medusajs.com/api/store#returns_postreturns) or [swap](https://docs.medusajs.com/api/store#swaps_postswaps) requests through the store APIs. The merchant can then review and handle these requests. This eliminates the need for the customer to perform the same action through customer support or other means. -You can also integrate these flows within bigger processes that trigger requesting or creating these flows. It can be done through core APIs, [custom endpoints](../../development/endpoints/overview.mdx), or [custom services](../../development/services/overview.mdx). You can also listen to events related to orders such as [Order](../../development/events/events-list.md#order-events) or [Swap](../../development/events/events-list.md#swap-events) events with [subscribers](../../development/events/subscribers.mdx) to perform asynchronous actions. +You can also integrate these flows within bigger processes that trigger requesting or creating these flows. It can be done through core APIs, [custom API Routes](../../development/api-routes/overview.mdx), or [custom services](../../development/services/overview.mdx). You can also listen to events related to orders such as [Order](../../development/events/events-list.md#order-events) or [Swap](../../development/events/events-list.md#swap-events) events with [subscribers](../../development/events/subscribers.mdx) to perform asynchronous actions. --- diff --git a/www/apps/docs/content/modules/orders/returns.md b/www/apps/docs/content/modules/orders/returns.md index 5f27aabb45..404f7983df 100644 --- a/www/apps/docs/content/modules/orders/returns.md +++ b/www/apps/docs/content/modules/orders/returns.md @@ -50,7 +50,7 @@ You can learn more about idempotency keys [here](../../development/idempotency-k This section explains how the return is created by the customer or any type of client. This is the process created within the Medusa core. -The following process occurs within the Create Return storefront endpoint: +The following process occurs within the Create Return storefront API Route: ![Return Client Process Flowchart](https://res.cloudinary.com/dza7lstvk/image/upload/v1681994516/Medusa%20Docs/Diagrams/return-client-process_evbjf5.jpg) @@ -63,7 +63,7 @@ After this process, the return will be available for the merchant or the admin t Marking a return as received would refund the amount to the customer and adjust the store’s inventory for the returned items. -The following process occurs within the [Receive Return admin endpoint](https://docs.medusajs.com/api/admin#returns_postreturnsreturnreceive): +The following process occurs within the [Receive Return admin API Route](https://docs.medusajs.com/api/admin#returns_postreturnsreturnreceive): ![Receive Return Process Flowchart](https://res.cloudinary.com/dza7lstvk/image/upload/v1681996834/Medusa%20Docs/Diagrams/return-admin-process_e99skk.jpg) @@ -79,7 +79,7 @@ The following process occurs within the [Receive Return admin endpoint](https:// ### Cancel a Return -The merchant can cancel a return if it hasn’t be marked as `received` before. This can be done either using the `ReturnService`'s [cancel method](../../references/services/classes/ReturnService.md#cancel) or using the [Cancel Return endpoint](https://docs.medusajs.com/api/admin#returns_postreturnsreturncancel). +The merchant can cancel a return if it hasn’t be marked as `received` before. This can be done either using the `ReturnService`'s [cancel method](../../references/services/classes/ReturnService.md#cancel) or using the [Cancel Return API Route](https://docs.medusajs.com/api/admin#returns_postreturnsreturncancel). Canceling a return would change its status to canceled. diff --git a/www/apps/docs/content/modules/orders/storefront/create-return.mdx b/www/apps/docs/content/modules/orders/storefront/create-return.mdx index d6ec7e7242..78ce31e2aa 100644 --- a/www/apps/docs/content/modules/orders/storefront/create-return.mdx +++ b/www/apps/docs/content/modules/orders/storefront/create-return.mdx @@ -57,7 +57,7 @@ When a customer wants to create a return, they must choose the items they want t ### Showing Return Shipping Options -You can optionally allow customers to choose a return shipping option that they’ll use to return the items. To show the customers the available return shipping options, send a request to the Get [Shipping Options endpoint](https://docs.medusajs.com/api/store#shipping-options_getshippingoptions): +You can optionally allow customers to choose a return shipping option that they’ll use to return the items. To show the customers the available return shipping options, send a request to the Get [Shipping Options API Route](https://docs.medusajs.com/api/store#shipping-options_getshippingoptions): @@ -121,7 +121,7 @@ fetch(`/store/shipping-options?is_return=true`, { -This endpoint allows you to pass the `is_return` query parameter to indicate whether the shipping options should be return shipping options. You can learn about other available filters in the [API reference](https://docs.medusajs.com/api/store#shipping-options_getshippingoptions). +This API Route allows you to pass the `is_return` query parameter to indicate whether the shipping options should be return shipping options. You can learn about other available filters in the [API reference](https://docs.medusajs.com/api/store#shipping-options_getshippingoptions). The request returns an array of shipping option objects. @@ -129,7 +129,7 @@ The request returns an array of shipping option objects. ## Step 2: Create Return -You can create the return by sending a request to the [Create Return endpoint](https://docs.medusajs.com/api/store#returns_postreturns): +You can create the return by sending a request to the [Create Return API Route](https://docs.medusajs.com/api/store#returns_postreturns): @@ -215,7 +215,7 @@ fetch(`/store/returns`, { -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `order_id`: a string indicating the ID of the order to create the return for. - `items`: an array of objects, each object being an item from the order to return. Each object must have the following properties: diff --git a/www/apps/docs/content/modules/orders/storefront/create-swap.mdx b/www/apps/docs/content/modules/orders/storefront/create-swap.mdx index c8f12017fb..aea1e74cf3 100644 --- a/www/apps/docs/content/modules/orders/storefront/create-swap.mdx +++ b/www/apps/docs/content/modules/orders/storefront/create-swap.mdx @@ -60,7 +60,7 @@ You can optionally allow customers to choose a return shipping option that they ## Step 2: Create the Swap -After collecting the swap details in step 1, you can create a swap in the Medusa backend by sending a request to the [Create Swap endpoint](https://docs.medusajs.com/api/store#swaps_postswaps): +After collecting the swap details in step 1, you can create a swap in the Medusa backend by sending a request to the [Create Swap API Route](https://docs.medusajs.com/api/store#swaps_postswaps): @@ -158,7 +158,7 @@ fetch(`/store/swaps`, { -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `order_id`: a string indicating the ID of the order that this swap is created for. - `return_items`: an array of objects, each object being the item to return. Each object should have the following properties: @@ -188,7 +188,7 @@ When you complete the cart, the returned `type` field can be used to indicate th ### Retrieve Swap by Cart ID -During your checkout flow, you might need to retrieve the swap using the cart’s ID. For example, if you want to display the swap’s details after the cart is successfully completed. You can do that using the [Get by Cart ID endpoint](https://docs.medusajs.com/api/store#swaps_getswapsswapcartid): +During your checkout flow, you might need to retrieve the swap using the cart’s ID. For example, if you want to display the swap’s details after the cart is successfully completed. You can do that using the [Get by Cart ID API Route](https://docs.medusajs.com/api/store#swaps_getswapsswapcartid): @@ -240,7 +240,7 @@ fetch(`/store/swaps/${cartId}`, { -This endpoint requires the ID of the cart as a path parameter. +This API Route requires the ID of the cart as a path parameter. The request returns the swap as an object. diff --git a/www/apps/docs/content/modules/orders/storefront/handle-order-edits.mdx b/www/apps/docs/content/modules/orders/storefront/handle-order-edits.mdx index 7d9cd35280..5c033b4566 100644 --- a/www/apps/docs/content/modules/orders/storefront/handle-order-edits.mdx +++ b/www/apps/docs/content/modules/orders/storefront/handle-order-edits.mdx @@ -70,7 +70,7 @@ You must have an existing order edit in the “request” state. ## Retrieve an Order Edit -You can retrieve a single order edit by its ID by sending a request to the [Get Order Edit](https://docs.medusajs.com/api/store#order-edits_getordereditsorderedit) endpoint: +You can retrieve a single order edit by its ID by sending a request to the [Get Order Edit API Route](https://docs.medusajs.com/api/store#order-edits_getordereditsorderedit): @@ -191,14 +191,14 @@ If `difference_due` is less than 0, then the amount will be refunded to the cust :::note -This section explains how to authorize the payment using one payment processor and payment session. However, payment collections allow customers to pay in installments or with more than one provider. You can learn more about how to do that using the [batch endpoints of the Payment APIs](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionssessionsbatchauthorize) +This section explains how to authorize the payment using one payment processor and payment session. However, payment collections allow customers to pay in installments or with more than one provider. You can learn more about how to do that using the [batch routes of the Payment APIs](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionssessionsbatchauthorize) ::: If `difference_due` is greater than 0, then additional payment from the customer is required. In this case, you must implement these steps to allow the customer to authorize the payment: 1. Show the customer the available payment processors. These can be retrieved from the details of [the region of the order](https://docs.medusajs.com/api/store#regions_getregions). -2. When the customer selects the payment processor, initialize the payment session of that provider in the payment collection. You can do that by sending a request to the [Manage Payment Sessions](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionspaymentcollectionsessionsbatch) endpoint, passing it the payment collection’s ID as a path parameter, and the payment processor's ID as a request body parameter: +2. When the customer selects the payment processor, initialize the payment session of that provider in the payment collection. You can do that by sending a request to the [Manage Payment Sessions API Route](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionspaymentcollectionsessionsbatch), passing it the payment collection’s ID as a path parameter, and the payment processor's ID as a request body parameter: @@ -267,7 +267,7 @@ fetch( 1. Show the customer the payment details form based on the payment session’s provider. For example, if the provider ID of a payment session is `stripe`, you must show Stripe’s card component to enter the customer’s card details. -2. Authorize the payment using the payment processor. The [Authorize Payment Session](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionssessionssessionauthorize) endpoint accepts the payment collection’s ID and the ID of the payment session as path parameters: +2. Authorize the payment using the payment processor. The [Authorize Payment Session API Route](https://docs.medusajs.com/api/store#payment-collections_postpaymentcollectionssessionssessionauthorize) accepts the payment collection’s ID and the ID of the payment session as path parameters: @@ -335,7 +335,7 @@ After performing the above steps, you can [complete the Order Edit](#complete-th ## Complete the Order Edit -To confirm and complete the order edit, send a request to the [Complete Order Edit](https://docs.medusajs.com/api/store#order-edits_postordereditsordereditcomplete) endpoint: +To confirm and complete the order edit, send a request to the [Complete Order Edit API Route](https://docs.medusajs.com/api/store#order-edits_postordereditsordereditcomplete): @@ -402,7 +402,7 @@ If the payment isn’t authorized first, the order edit completion will fail. ## Decline an Order Edit -If the customer wants to decline the Order Edit, you can do that by sending a request to the Decline Order Edit endpoint: +If the customer wants to decline the Order Edit, you can do that by sending a request to the Decline Order Edit API Route: diff --git a/www/apps/docs/content/modules/orders/storefront/implement-claim-order.mdx b/www/apps/docs/content/modules/orders/storefront/implement-claim-order.mdx index 51e541271f..74c1619303 100644 --- a/www/apps/docs/content/modules/orders/storefront/implement-claim-order.mdx +++ b/www/apps/docs/content/modules/orders/storefront/implement-claim-order.mdx @@ -77,7 +77,7 @@ In addition, it is assumed you already have a logged-in customer before performi When the customer wants to claim an order, they must supply its ID. -To allow the customer to claim an order, send a request to the Claim an Order endpoint: +To allow the customer to claim an order, send a request to the Claim an Order API Route: @@ -135,7 +135,7 @@ The customer at this point will receive an email with a link to verify their cla The link in the email that the customer receives should be a page in your storefront that accepts a `token` query parameter. -Then, you send a request to the Verify Claim Order endpoint: +Then, you send a request to the Verify Claim Order API Route: diff --git a/www/apps/docs/content/modules/orders/storefront/retrieve-order-details.mdx b/www/apps/docs/content/modules/orders/storefront/retrieve-order-details.mdx index bddbe21d36..4caa61e165 100644 --- a/www/apps/docs/content/modules/orders/storefront/retrieve-order-details.mdx +++ b/www/apps/docs/content/modules/orders/storefront/retrieve-order-details.mdx @@ -36,7 +36,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus Retrieving an order by its ID is useful for different scenarios, such as using an order details page. You can use this method for both logged in and guest customers. -You can retrieve an order by its ID using the [Get Order endpoint](https://docs.medusajs.com/api/store#orders_getordersorder): +You can retrieve an order by its ID using the [Get Order API Route](https://docs.medusajs.com/api/store#orders_getordersorder): @@ -88,7 +88,7 @@ fetch(`/store/orders/${orderId}`, { -This endpoint requires the order’s ID to be passed as a path parameter. You can utilize the [expand](https://docs.medusajs.com/api/store#expanding-fields) and [fields](https://docs.medusajs.com/api/store#selecting-fields) query parameters to select parameters and relations to return. +This API Route requires the order’s ID to be passed as a path parameter. You can utilize the [expand](https://docs.medusajs.com/api/store#expanding-fields) and [fields](https://docs.medusajs.com/api/store#selecting-fields) query parameters to select parameters and relations to return. The request returns the order as an object. @@ -98,7 +98,7 @@ The request returns the order as an object. Display IDs allow you to show human-readable IDs to your customers. Retrieving an order by its display ID is useful in many situations, such as allowing customers to look up their orders with a search field. This method of retrieving an order can be used for both logged-in customers and guest customers. -You can retrieve an order by its display ID using the [Look Up Order endpoint](https://docs.medusajs.com/api/store#orders_getorders): +You can retrieve an order by its display ID using the [Look Up Order API Route](https://docs.medusajs.com/api/store#orders_getorders): @@ -158,12 +158,12 @@ fetch(`/store/orders?display_id=1&email=user@example.com`, { -This endpoint requires two query parameters: +This API Route requires two query parameters: - `display_id`: a string indicating display ID of the order. If you already have an order object, you can retrieve the display ID using `order.display_id`. - `email`: a string indicating the email associated with the order. -You can pass other query parameters to filter the orders even further, and the endpoint will return the first order that matches the filters. Learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/store#orders_getorders). +You can pass other query parameters to filter the orders even further, and the API Route will return the first order that matches the filters. Learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/store#orders_getorders). The request returns the order as an object. @@ -173,7 +173,7 @@ The request returns the order as an object. In certain scenarios, you may need to retrieve an order’s details using the ID of the cart associated with the order. This can be useful when showing a success page after a cart is completed and an order is placed. -You can retrieve an order by the cart ID using the [Get by Cart ID endpoint](https://docs.medusajs.com/api/store#orders_getordersordercartid): +You can retrieve an order by the cart ID using the [Get by Cart ID API Route](https://docs.medusajs.com/api/store#orders_getordersordercartid): @@ -225,7 +225,7 @@ fetch(`/store/orders/cart/${cartId}`, { -This endpoint requires the ID of the cart as a path parameter. +This API Route requires the ID of the cart as a path parameter. The request returns the order as an object. diff --git a/www/apps/docs/content/modules/orders/swaps.md b/www/apps/docs/content/modules/orders/swaps.md index 7de6ea4075..dd2d59fcac 100644 --- a/www/apps/docs/content/modules/orders/swaps.md +++ b/www/apps/docs/content/modules/orders/swaps.md @@ -47,7 +47,7 @@ You can learn more about idempotency keys [here](../../development/idempotency-k ### Swap Creation Process -The customer starts by creating their swap, which can be done through the Create Swap endpoint. In this endpoint, the following steps are implemented: +The customer starts by creating their swap, which can be done through the Create Swap API Route. In this API Route, the following steps are implemented: ![Swap Creation Flowchart](https://res.cloudinary.com/dza7lstvk/image/upload/v1681983755/Medusa%20Docs/Diagrams/swap-process_kylqq0.jpg) @@ -69,7 +69,7 @@ This is all made possible since the swap is linked to a cart, so the same checko After the swap has been created and completed by the customer, the merchant can then process the payment of the swap. This includes either refunding or capturing an additional payment, which is decided by the value of the `difference_due` attribute as explained in the [Swap Entity section](#swap-entity-overview). -The processing of the swap’s payment can be done either using the `SwapService`'s [processDifference method](../../references/services/classes/SwapService.md#processdifference), or using the [Process Swap Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapprocesspayment). +The processing of the swap’s payment can be done either using the `SwapService`'s [processDifference method](../../references/services/classes/SwapService.md#processdifference), or using the [Process Swap Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapprocesspayment). If the swap requires any additional payment, the customer is expected to have authorized the payment during the [swap and cart completion flow explained earlier](#how-are-swaps-created). The merchant can then capture the payment and the `payment_status` of the swap is set to `captured`. @@ -89,9 +89,9 @@ Although you have freedom in how you implement the process, the recommended proc ![Swap Fulfillment Flowchart](https://res.cloudinary.com/dza7lstvk/image/upload/v1681984933/Medusa%20Docs/Diagrams/swap-fulfillment-process_xfurko.jpg) -1. The fulfillment is created either using the `SwapService`'s [createFulfillment method](../../references/services/classes/SwapService.md#createfulfillment) or using the [Create a Swap Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapfulfillments). This would set the `fulfillment_status` of the swap either to `fulfilled` if all items have been fulfilled, or `partially_fulfilled` if only some items were fulfilled. -2. The shipment can then be created using the `SwapService`'s [createShipment method](../../references/services/classes/SwapService.md#createshipment) or using the [Create Swap Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapshipments). This would set the `fulfillment_status` of the swap either to `shipped` if all items have been shipped, or `partially_shipped` if only some items were shipped. -3. Alternatively, a fulfillment can be canceled after it has been created using the `SwapService`'s [cancelFulfillment method](../../references/services/classes/SwapService.md#cancelfulfillment) or using the [Cancel Swap’s Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersswapfulfillmentscancel). This would set the `fulfillment_status` of the swap to `canceled`. +1. The fulfillment is created either using the `SwapService`'s [createFulfillment method](../../references/services/classes/SwapService.md#createfulfillment) or using the [Create a Swap Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapfulfillments). This would set the `fulfillment_status` of the swap either to `fulfilled` if all items have been fulfilled, or `partially_fulfilled` if only some items were fulfilled. +2. The shipment can then be created using the `SwapService`'s [createShipment method](../../references/services/classes/SwapService.md#createshipment) or using the [Create Swap Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderswapsswapshipments). This would set the `fulfillment_status` of the swap either to `shipped` if all items have been shipped, or `partially_shipped` if only some items were shipped. +3. Alternatively, a fulfillment can be canceled after it has been created using the `SwapService`'s [cancelFulfillment method](../../references/services/classes/SwapService.md#cancelfulfillment) or using the [Cancel Swap’s Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersswapfulfillmentscancel). This would set the `fulfillment_status` of the swap to `canceled`. A swap’s fulfillments can be accessed by expanding the `fulfillments` relation and accessing `swap.fulfillments`. A fulfillment is represented by the `Fulfillment` entity. @@ -105,7 +105,7 @@ A swap's return can be marked as received, which would adjust the inventory and ## Canceling a Swap -A swap can be canceled by the merchant if necessary. It can be done either through the `SwapService`'s [cancel method](../../references/services/classes/SwapService.md#cancel) or the [Cancel Swap endpoint](https://docs.medusajs.com/api/admin#orders_postordersswapcancel). +A swap can be canceled by the merchant if necessary. It can be done either through the `SwapService`'s [cancel method](../../references/services/classes/SwapService.md#cancel) or the [Cancel Swap API Route](https://docs.medusajs.com/api/admin#orders_postordersswapcancel). A swap can’t be canceled if: diff --git a/www/apps/docs/content/modules/price-lists/admin/_import-prices.mdx b/www/apps/docs/content/modules/price-lists/admin/_import-prices.mdx index 8e486f4a12..bc9308d244 100644 --- a/www/apps/docs/content/modules/price-lists/admin/_import-prices.mdx +++ b/www/apps/docs/content/modules/price-lists/admin/_import-prices.mdx @@ -137,7 +137,7 @@ You can learn more about [authenticating as an admin user in the API reference]( Before importing the prices, you must have a price list to import them to. -You can use the [Create Price List](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelist) endpoint, or follow the [how-to guide to learn how to create and manage price lists using the Admin API](./manage-price-lists.mdx). +You can use the [Create Price List API Route](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelist), or follow the [how-to guide to learn how to create and manage price lists using the Admin API](./manage-price-lists.mdx). --- @@ -145,7 +145,7 @@ You can use the [Create Price List](https://docs.medusajs.com/api/admin#price-li The first step is to upload the CSV file to import prices from. -You can do that by sending the following request to the [Upload Files](https://docs.medusajs.com/api/admin#uploads_postuploads) endpoint: +You can do that by sending the following request to the [Upload Files API Route](https://docs.medusajs.com/api/admin#uploads_postuploads): @@ -219,7 +219,7 @@ This request returns an array of uploads. Each item in the array is an object th To start a new price import, you must create a batch job. -You can do that by sending the following request to the [Create a Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) endpoint: +You can do that by sending the following request to the [Create a Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs): diff --git a/www/apps/docs/content/modules/price-lists/admin/manage-price-lists.mdx b/www/apps/docs/content/modules/price-lists/admin/manage-price-lists.mdx index 94af2251f7..f9f4fe2353 100644 --- a/www/apps/docs/content/modules/price-lists/admin/manage-price-lists.mdx +++ b/www/apps/docs/content/modules/price-lists/admin/manage-price-lists.mdx @@ -230,7 +230,7 @@ You can check the full list of request body parameters in the [API reference](ht ## Get Price List’s Details -You can retrieve all of a price list’s details using the Get a Price List endpoint: +You can retrieve all of a price list’s details using the Get a Price List API Route: @@ -294,7 +294,7 @@ curl -L -X GET '/admin/price-lists/{id}' \ ## Update a Price List -After creating a price list, you can update all of its fields including its status, prices, and more using the [Update Price List](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelistpricelist) endpoint. +After creating a price list, you can update all of its fields including its status, prices, and more using the [Update Price List API Route](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelistpricelist). For example, by sending the following request the end date of the price list will be updated: @@ -381,7 +381,7 @@ For a full list of request body parameters, check out the [API reference](https: ### Add Prices -You can add prices to your price list after creating it using the [Update Prices](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelistpricesbatch) endpoint. +You can add prices to your price list after creating it using the [Update Prices API Route](https://docs.medusajs.com/api/admin#price-lists_postpricelistspricelistpricesbatch). You can also set the `override` request body parameter to `true` to replace the existing prices in the price list. @@ -488,7 +488,7 @@ For a full list of request body parameters, check out the [API reference](https: ### Delete a Product’s Prices -You can delete all the prices of a product’s variants using the [Delete Product Prices](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelistpricesbatch) endpoint: +You can delete all the prices of a product’s variants using the [Delete Product Prices API Route](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelistpricesbatch): @@ -562,7 +562,7 @@ This request returns the IDs of the deleted prices. ### Delete a Variant’s Prices -You can delete all the prices of a variant using the [Delete Variant Prices](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelistvariantsvariantprices) endpoint: +You can delete all the prices of a variant using the [Delete Variant Prices API Route](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelistvariantsvariantprices): @@ -639,7 +639,7 @@ This request returns the IDs of the deleted prices. ## Delete Price List -You can delete a price list, and subsequently all prices defined in it, using the [Delete Price List](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelist) endpoint: +You can delete a price list, and subsequently all prices defined in it, using the [Delete Price List API Route](https://docs.medusajs.com/api/admin#price-lists_deletepricelistspricelist): diff --git a/www/apps/docs/content/modules/price-lists/backend/override-price-selection-strategy.md b/www/apps/docs/content/modules/price-lists/backend/override-price-selection-strategy.md index aea7e14b1d..f820118e78 100644 --- a/www/apps/docs/content/modules/price-lists/backend/override-price-selection-strategy.md +++ b/www/apps/docs/content/modules/price-lists/backend/override-price-selection-strategy.md @@ -125,4 +125,4 @@ Run your backend to test it out: npx medusa develop ``` -Then, try out your strategy using any of the [Products](https://docs.medusajs.com/api/store#products) or [Carts](https://docs.medusajs.com/api/store#carts) endpoints which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy. +Then, try out your strategy using any of the [Products](https://docs.medusajs.com/api/store#products) or [Carts](https://docs.medusajs.com/api/store#carts) API Routes which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy. diff --git a/www/apps/docs/content/modules/price-lists/price-lists.md b/www/apps/docs/content/modules/price-lists/price-lists.md index 5f71f197ac..fb6eccf564 100644 --- a/www/apps/docs/content/modules/price-lists/price-lists.md +++ b/www/apps/docs/content/modules/price-lists/price-lists.md @@ -61,7 +61,7 @@ The original price depends on the selected region or currency code in the curren The calculated price is the lowest price among all retrieved prices. Retrieved prices can include the original price and the price lists that can be applied. Prices are retrieved based on the [context](./price-selection-strategy.md#context-object). -In the [Get Product](https://docs.medusajs.com/api/store#products_getproductsproduct) and [List Product](https://docs.medusajs.com/api/store#products_getproducts) endpoints, you must pass either the `region_id` or `currency_code` to retrieve the correct prices, as they are part of the price selection strategy context. +In the [Get Product](https://docs.medusajs.com/api/store#products_getproductsproduct) and [List Product](https://docs.medusajs.com/api/store#products_getproducts) API Routes, you must pass either the `region_id` or `currency_code` to retrieve the correct prices, as they are part of the price selection strategy context. Each variant in the response has the following properties: @@ -76,7 +76,7 @@ The total of a line item depends on the price of a product variant. When the lin Then, the `unit_price` of the line item is set to the `calculated_price` property of the product variant. -When creating, retrieving, or updating the line item using the API endpoints, the line item’s totals are calculated. The following properties are returned as part of the endpoints’ responses: +When creating, retrieving, or updating the line item using the API Routes, the line item’s totals are calculated. The following properties are returned as part of the API Routes' responses: - `unit_price`: The product variant’s calculated price. - `subtotal`: The `unit_price` multiplied by the quantity of the line item. diff --git a/www/apps/docs/content/modules/products/admin/import-products.mdx b/www/apps/docs/content/modules/products/admin/import-products.mdx index b485f67a83..002c6fadec 100644 --- a/www/apps/docs/content/modules/products/admin/import-products.mdx +++ b/www/apps/docs/content/modules/products/admin/import-products.mdx @@ -868,7 +868,7 @@ You can learn more about [authenticating as an admin user in the API reference]( The first step is to upload the CSV file that you want to import products. -You can do that by sending the following request to the [Upload Files](https://docs.medusajs.com/api/admin#uploads_postuploads) endpoint: +You can do that by sending the following request to the [Upload Files API Route](https://docs.medusajs.com/api/admin#uploads_postuploads): @@ -943,7 +943,7 @@ Where `` is a full path to the file. For example, `/Users/medusa/pr To start a new product import, you must create a batch job. -You can do that by sending the following request to the [Create a Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) endpoint: +You can do that by sending the following request to the [Create a Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs): diff --git a/www/apps/docs/content/modules/products/admin/manage-categories.mdx b/www/apps/docs/content/modules/products/admin/manage-categories.mdx index 0663d33961..58123f220f 100644 --- a/www/apps/docs/content/modules/products/admin/manage-categories.mdx +++ b/www/apps/docs/content/modules/products/admin/manage-categories.mdx @@ -51,7 +51,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Categories -You can retrieve available categories by sending a request to the [List Categories](https://docs.medusajs.com/api/admin#product-categories_getproductcategories) endpoint: +You can retrieve available categories by sending a request to the [List Categories API Route](https://docs.medusajs.com/api/admin#product-categories_getproductcategories): @@ -131,7 +131,7 @@ You can also pass filters and other selection query parameters to the request. C ## Create a Category -You can create a category by sending a request to the [Create a Category](https://docs.medusajs.com/api/admin#product-categories_postproductcategories) endpoint: +You can create a category by sending a request to the [Create a Category API Route](https://docs.medusajs.com/api/admin#product-categories_postproductcategories): @@ -215,7 +215,7 @@ The request returns the newly created product category. ## Retrieve a Category -You can retrieve a product category by sending a request to the [Get a Product Category](https://docs.medusajs.com/api/admin#product-categories_getproductcategoriescategory) endpoint: +You can retrieve a product category by sending a request to the [Get a Product Category API Route](https://docs.medusajs.com/api/admin#product-categories_getproductcategoriescategory): @@ -285,7 +285,7 @@ It returns the full object of the product category. ## Edit a Category -You can edit a product category by sending a request to the [Update a Product Category](https://docs.medusajs.com/api/admin#product-categories_postproductcategoriescategory) endpoint: +You can edit a product category by sending a request to the [Update a Product Category API Route](https://docs.medusajs.com/api/admin#product-categories_postproductcategoriescategory): @@ -380,7 +380,7 @@ You can manage the categories of each product individually using the [product AP ### Add Products to a Category -You can add more than one product to a category using the [Add Products to a Category](https://docs.medusajs.com/api/admin#product-categories_postproductcategoriescategoryproductsbatch) endpoint: +You can add more than one product to a category using the [Add Products to a Category API Route](https://docs.medusajs.com/api/admin#product-categories_postproductcategoriescategoryproductsbatch): @@ -491,7 +491,7 @@ The request returns the full object of the product category updated with the new ### Remove Products from a Category -You can remove products from a category by sending a request to the [Delete Products](https://docs.medusajs.com/api/admin#product-categories_deleteproductcategoriescategoryproductsbatch) endpoint: +You can remove products from a category by sending a request to the [Delete Products API Route](https://docs.medusajs.com/api/admin#product-categories_deleteproductcategoriescategoryproductsbatch): @@ -608,7 +608,7 @@ The request returns the full object of the product category updated with the its ## Delete a Category -You can delete a product category by sending a request to the [Delete a Product Category](https://docs.medusajs.com/api/admin#product-categories_deleteproductcategoriescategory) endpoint: +You can delete a product category by sending a request to the [Delete a Product Category API Route](https://docs.medusajs.com/api/admin#product-categories_deleteproductcategoriescategory): diff --git a/www/apps/docs/content/modules/products/admin/manage-products.mdx b/www/apps/docs/content/modules/products/admin/manage-products.mdx index 9755d19043..f48bdbc5e0 100644 --- a/www/apps/docs/content/modules/products/admin/manage-products.mdx +++ b/www/apps/docs/content/modules/products/admin/manage-products.mdx @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Products -You can list products as an admin using the [List Products endpoint](https://docs.medusajs.com/api/admin#products_getproducts): +You can list products as an admin using the [List Products API Route](https://docs.medusajs.com/api/admin#products_getproducts): @@ -115,7 +115,7 @@ curl -L -X GET '/admin/products' \ -This endpoint does not require any parameters. You can pass parameters to search and filter through the retrieved products. For example, you can pass the `q` parameter which searches through product titles, descriptions, and more. You can learn more about available parameters in the [API reference](https://docs.medusajs.com/api/admin#products_getproducts). +This API Route doesn't require any parameters. You can pass parameters to search and filter through the retrieved products. For example, you can pass the `q` parameter which searches through product titles, descriptions, and more. You can learn more about available parameters in the [API reference](https://docs.medusajs.com/api/admin#products_getproducts). You can also specify which fields to returns or which relations to expand using the `fields` and `expand` query parameters. You can learn more about them in the [API reference](https://docs.medusajs.com/api/admin#expanding-fields). @@ -125,7 +125,7 @@ The request returns an array of products along with [pagination parameters](http ## Create a Product -You can create a product by sending a request to the [Create a Product endpoint](https://docs.medusajs.com/api/admin#products_postproducts): +You can create a product by sending a request to the [Create a Product API Route](https://docs.medusajs.com/api/admin#products_postproducts): @@ -365,7 +365,7 @@ curl -L -X POST '/admin/products' \ -This endpoint only requires the `title` body parameter, which is the name of the product. Other parameters passed in the example are optional. They are: +This API Route only requires the `title` body parameter, which is the name of the product. Other parameters passed in the example are optional. They are: - `is_giftcard`: a boolean value that determines whether a product is a gift card. By default, it’s `false`. - `is_discountable`: a boolean value that determines whether discounts can be applied on the product. By default, it’s `true`. @@ -399,7 +399,7 @@ You can learn more about pricing and zero-decimal currencies [here](../products. ## Retrieve a Product -You can retrieve a single product as an admin by sending a request to the [Get a Product endpoint](https://docs.medusajs.com/api/admin#products_getproductsproduct): +You can retrieve a single product as an admin by sending a request to the [Get a Product API Route](https://docs.medusajs.com/api/admin#products_getproductsproduct): @@ -459,7 +459,7 @@ curl -L -X GET '/admin/products/' \ -This endpoint requires the product ID to be passed as a path parameter. +This API Route requires the product ID to be passed as a path parameter. The request returns the product as an object. @@ -467,7 +467,7 @@ The request returns the product as an object. ## Update a Product -You can update a product by sending a request to the [Update Product endpoint](https://docs.medusajs.com/api/admin#products_postproductsproduct): +You can update a product by sending a request to the [Update Product API Route](https://docs.medusajs.com/api/admin#products_postproductsproduct): @@ -540,7 +540,7 @@ curl -L -X POST '/admin/products/' \ -This endpoint requires the product ID as a path parameter. In the request’s body, you can pass any of the product’s fields to update. In the example above, you update the `title` of the product. +This API Route requires the product ID as a path parameter. In the request’s body, you can pass any of the product’s fields to update. In the example above, you update the `title` of the product. You can learn about other body parameters that you can pass in the [API reference](https://docs.medusajs.com/api/admin#products_postproductsproduct). @@ -550,15 +550,15 @@ The request returns the updated product as an object. ## Manage Product Options -In this section, you’ll learn how to manage the options of the product. Although you can already do that through the [Create a Product](#create-a-product) and [Update a Product](#update-a-product) endpoints explained above, you can also use endpoints specific to product options. +In this section, you’ll learn how to manage the options of the product. Although you can already do that through the [Create a Product](#create-a-product) and [Update a Product](#update-a-product) API Routes explained above, you can also use API Routes specific to product options. ### Retrieve Product Options -You can retrieve a product’s options by retrieving the product either using the [List Products](#list-products) or the [Retrieve a Product](#retrieve-a-product) endpoints. The options are available under the `options` property. +You can retrieve a product’s options by retrieving the product either using the [List Products](#list-products) or the [Retrieve a Product](#retrieve-a-product) API Routes. The options are available under the `options` property. ### Add a Product Option -You can add a product option to a product by sending a request to the [Add Product Option endpoint](https://docs.medusajs.com/api/admin#products_postproductsproductoptions): +You can add a product option to a product by sending a request to the [Add Product Option API Route](https://docs.medusajs.com/api/admin#products_postproductsproductoptions): @@ -631,13 +631,13 @@ curl -L -X POST '/admin/products//options' \ -This endpoint requires the product’s ID as a path parameter. In the request body parameter, it requires passing the `title` of the option. +This API Route requires the product’s ID as a path parameter. In the request body parameter, it requires passing the `title` of the option. The request returns the updated product as an option. You can view available options under the `options` property of the product. ### Update a Product Option -You can update a product option by sending a request to the [Update Product Option endpoint](https://docs.medusajs.com/api/admin#products_postproductsproductoptionsoption): +You can update a product option by sending a request to the [Update Product Option API Route](https://docs.medusajs.com/api/admin#products_postproductsproductoptionsoption): @@ -713,7 +713,7 @@ curl -L -X POST '/admin/products//options/' \ -This endpoint requires the product’s ID and the product option’s ID to be passed as a path parameter. +This API Route requires the product’s ID and the product option’s ID to be passed as a path parameter. In the body parameters, you can update the `title` field of the product option. @@ -721,7 +721,7 @@ The request returns the updated product as an option. You can view available opt ### Delete a Product Option -You can delete a product option by sending a request to the [Delete Product Option endpoint](https://docs.medusajs.com/api/admin#products_deleteproductsproductoptionsoption): +You can delete a product option by sending a request to the [Delete Product Option API Route](https://docs.medusajs.com/api/admin#products_deleteproductsproductoptionsoption): @@ -782,7 +782,7 @@ curl -L -X DELETE '/admin/products//options/' \ -This endpoint requires the product’s ID and the product option’s ID to be passed as a path parameter. +This API Route requires the product’s ID and the product option’s ID to be passed as a path parameter. The request returns the following fields: @@ -795,15 +795,15 @@ The request returns the following fields: ## Manage Product Variants -In this section, you’ll learn how to manage the variants of the product. Although you can already do that through the [Create a Product](#create-a-product) and [Update a Product](#update-a-product) endpoints explained above, you can also use endpoints specific to product variants. +In this section, you’ll learn how to manage the variants of the product. Although you can already do that through the [Create a Product](#create-a-product) and [Update a Product](#update-a-product) API Routes explained above, you can also use API Routes specific to product variants. ### Retrieve Product Variants -You can retrieve a product’s variants by retrieving the product either using the [List Products](#list-products) or the [Retrieve a Product](#retrieve-a-product) endpoints. The product variants are available under the `variants` property. +You can retrieve a product’s variants by retrieving the product either using the [List Products](#list-products) or the [Retrieve a Product](#retrieve-a-product) API Routes. The product variants are available under the `variants` property. ### Create Product Variants -You can create a product variant by sending a request to the [Create Product Variant endpoint](https://docs.medusajs.com/api/admin#products_postproductsproductvariants): +You can create a product variant by sending a request to the [Create Product Variant API Route](https://docs.medusajs.com/api/admin#products_postproductsproductvariants): @@ -924,7 +924,7 @@ curl -L -X POST '/admin/products//variants' \ -This endpoint requires the ID of the product as a path parameter. In the request body parameters, the following parameters are required: +This API Route requires the ID of the product as a path parameter. In the request body parameters, the following parameters are required: - `title`: A string indicating the title of the product variant. - `prices`: an array of objects, each object indicating the pricing of the variant in different contexts. For example, you can specify different prices for different currencies or regions. You can learn about other accepted properties within price objects in the API reference. You can also learn about formatting the `amount` property in this section. @@ -938,7 +938,7 @@ The request returns the updated product. You can access the product’s variants ### Update a Product Variant -You can update a product variant by sending a request to the [Update a Product Variant endpoint](https://docs.medusajs.com/api/admin#products_postproductsproductvariantsvariant): +You can update a product variant by sending a request to the [Update a Product Variant API Route](https://docs.medusajs.com/api/admin#products_postproductsproductvariantsvariant): @@ -1014,7 +1014,7 @@ curl -L -X POST '/admin/products//variants/ -This endpoint requires the product ID and variant ID to be passed as a path parameter. +This API Route requires the product ID and variant ID to be passed as a path parameter. In the request body parameters, you can pass any of the variant’s attributes that you want to update. In the example above, you edit the `title` of the variant. You can refer to the [API reference](https://docs.medusajs.com/api/admin#products_postproductsproductvariantsvariant) for other possible parameters. @@ -1022,7 +1022,7 @@ The request returns the updated product. You can access the product’s variants ### Delete Product Variant -You can delete a product variant by sending a request to the [Delete a Product Variant endpoint](https://docs.medusajs.com/api/admin#products_deleteproductsproductvariantsvariant): +You can delete a product variant by sending a request to the [Delete a Product Variant API Route](https://docs.medusajs.com/api/admin#products_deleteproductsproductvariantsvariant): @@ -1083,7 +1083,7 @@ curl -L -X DELETE '/admin/products//variants/ -This endpoint requires the product ID and variant ID to be passed as a path parameter. +This API Route requires the product ID and variant ID to be passed as a path parameter. The request returns the following fields: @@ -1096,7 +1096,7 @@ The request returns the following fields: ## Delete a Product -You can delete a product by sending a request to the [Delete a Product endpoint](https://docs.medusajs.com/api/admin#products_deleteproductsproduct): +You can delete a product by sending a request to the [Delete a Product API Route](https://docs.medusajs.com/api/admin#products_deleteproductsproduct): @@ -1155,7 +1155,7 @@ curl -L -X DELETE '/admin/products/' \ -This endpoint requires passing the product ID as a path parameter. +This API Route requires passing the product ID as a path parameter. The request returns the following fields: diff --git a/www/apps/docs/content/modules/products/categories.md b/www/apps/docs/content/modules/products/categories.md index 8d88fe6c3f..d950f66fbc 100644 --- a/www/apps/docs/content/modules/products/categories.md +++ b/www/apps/docs/content/modules/products/categories.md @@ -82,7 +82,7 @@ The relation is implemented in the Product entity. You can access the product The parent-child hierarchy is represented in the `ProductCategory` entity through the following relations: - You can access the parent of a category by expanding the `parent_category` relation and accessing `category.parent_category`. You can also access the ID of the parent category by accessing `category.parent_category_id`. If a category doesn’t have a parent, the relation and the ID will be `null`. -- You can access the children of a category by expanding the `category_children` relation and accessing `category.category_children`. If a category doesn’t have children, the relation will be an empty array. By default, when expanding this relation in Product Category endpoints, only the immediate child categories are returned. If you want to get the entire hierarchy of child categories, you must pass the `include_descendants_tree` flag to the endpoint setting its value to `true`. +- You can access the children of a category by expanding the `category_children` relation and accessing `category.category_children`. If a category doesn’t have children, the relation will be an empty array. By default, when expanding this relation in Product Category API Routes, only the immediate child categories are returned. If you want to get the entire hierarchy of child categories, you must pass the `include_descendants_tree` flag to the API Route setting its value to `true`. Aside from these relations, the `mpath` attribute, which is a [Materialized Path](https://typeorm.io/tree-entities#materialized-path-aka-path-enumeration) that is automatically generated by Typeorm, can be used to query deep trees faster. diff --git a/www/apps/docs/content/modules/products/serverless-module.md b/www/apps/docs/content/modules/products/serverless-module.md index 72ccd98002..8ab08666e0 100644 --- a/www/apps/docs/content/modules/products/serverless-module.md +++ b/www/apps/docs/content/modules/products/serverless-module.md @@ -225,7 +225,7 @@ module.exports = nextConfig ### Step 5: Create API Route -The product module is ready for use now! You can now use it to create API endpoints within your Next.js application. +The product module is ready for use now! You can now use it to create API routes within your Next.js application. :::note @@ -251,11 +251,11 @@ export async function GET(request: Request) { } ``` -This creates a `GET` endpoint at the route `/api/products`. You import the `initialize` function, aliased as `initializeProductModule`, from `@medusajs/product`. Then, in the endpoint, you invoke the `initializeProductModule` function, which returns an instance of the `ProductModuleService`. Using the product module service’s `list` method, you retrieve all available products and return them in the response of the endpoint. +This creates a `GET` API route at the path `/api/products`. You import the `initialize` function, aliased as `initializeProductModule`, from `@medusajs/product`. Then, in the API route, you invoke the `initializeProductModule` function, which returns an instance of the `ProductModuleService`. Using the product module service’s `list` method, you retrieve all available products and return them in the response. ### Step 6: Test Next.js Application -To test the endpoint you added, start your Next.js application with the following command: +To test the API route you added, start your Next.js application with the following command: ```bash npm2yarn npm run dev @@ -267,7 +267,7 @@ Then, open in your browser the URL `http://localhost:3000/api/products`. If you ## Example Usages -This section includes some examples of the different functionalities or ways you can use the product module. The code snippets are shown in the context of endpoints. +This section includes some examples of the different functionalities or ways you can use the product module. The code snippets are shown in the context of API routes. ### List Products diff --git a/www/apps/docs/content/modules/products/storefront/show-products.mdx b/www/apps/docs/content/modules/products/storefront/show-products.mdx index 452bbaafe3..bb989afc6e 100644 --- a/www/apps/docs/content/modules/products/storefront/show-products.mdx +++ b/www/apps/docs/content/modules/products/storefront/show-products.mdx @@ -56,7 +56,7 @@ If you follow the `@medusajs/product` code blocks, it's assumed you already have ## List Products -You can list available products using the [List Products endpoint](https://docs.medusajs.com/api/store#products_getproducts): +You can list available products using the [List Products API Route](https://docs.medusajs.com/api/store#products_getproducts): @@ -143,13 +143,13 @@ curl -L -X GET '/store/products' -This endpoint does not require any parameters. You can pass it parameters related to pagination, filtering, and more as explained in the [API reference](https://docs.medusajs.com/api/store#tag/Products/operation/GetProducts). +This API Route doesn't require any parameters. You can pass it parameters related to pagination, filtering, and more as explained in the [API reference](https://docs.medusajs.com/api/store#tag/Products/operation/GetProducts). The request returns an array of product objects along with [pagination parameters](https://docs.medusajs.com/api/store#section/Pagination). ### Filtering Retrieved Products -The List Products endpoint accepts different query parameters that allow you to filter through retrieved results. +The List Products API Route accepts different query parameters that allow you to filter through retrieved results. For example, you can filter products by a category ID: @@ -588,7 +588,7 @@ The Search functionality requires either installing a [search plugin](../../../p ::: -You can search products using the [Search Products endpoint](https://docs.medusajs.com/api/store#tag/Products/operation/PostProductsSearch): +You can search products using the [Search Products API Route](https://docs.medusajs.com/api/store#tag/Products/operation/PostProductsSearch): @@ -636,7 +636,7 @@ curl -L -X POST '/store/products/search?q=Shirt' \ -This endpoint requires the query parameter `q` being the term to search products for. The search plugin or service you’re using determine how `q` will be used to search the products. It also accepts pagination parameters as explained in the [API reference](https://docs.medusajs.com/api/store#products_postproductssearch). +This API Route requires the query parameter `q` being the term to search products for. The search plugin or service you’re using determine how `q` will be used to search the products. It also accepts pagination parameters as explained in the [API reference](https://docs.medusajs.com/api/store#products_postproductssearch). The request returns a `hits` array holding the result items. The structure of the items depends on the plugin you’re using. @@ -644,7 +644,7 @@ The request returns a `hits` array holding the result items. The structure of th ## Retrieve a Product by ID -You can retrieve the details of a single product by its ID using the [Get a Product endpoint](https://docs.medusajs.com/api/store#products_getproductsproduct): +You can retrieve the details of a single product by its ID using the [Get a Product API Route](https://docs.medusajs.com/api/store#products_getproductsproduct): @@ -726,7 +726,7 @@ curl -L -X GET '/store/products/' -This endpoint requires the product’s ID to be passed as a path parameter. You can also pass query parameters such as `cart_id` and `region_id` which are relevant for pricing as explained in the [Product Pricing Parameters section](#product-pricing-parameters). You can check the full list of accepted parameters in the [API reference](https://docs.medusajs.com/api/store#products_getproductsproduct). +This API Route requires the product’s ID to be passed as a path parameter. You can also pass query parameters such as `cart_id` and `region_id` which are relevant for pricing as explained in the [Product Pricing Parameters section](#product-pricing-parameters). You can check the full list of accepted parameters in the [API reference](https://docs.medusajs.com/api/store#products_getproductsproduct). The request returns a product object. You can display its price as explained in the [Display Product Price](#display-product-price) section. @@ -738,7 +738,7 @@ You can also retrieve the product's categories by passing the `expand` query par On the storefront, you may use the handle of a product as its page’s path. For example, instead of displaying the product’s details on the path `/products/prod_123`, you can display it on the path `/products/shirt`, where `shirt` is the handle of the product. This type of URL is human-readable and is good for Search Engine Optimization (SEO) -You can retrieve the details of a product by its handle by sending a request to the List Products endpoint, passing the `handle` as a filter: +You can retrieve the details of a product by its handle by sending a request to the List Products API Route, passing the `handle` as a filter: diff --git a/www/apps/docs/content/modules/products/storefront/use-categories.mdx b/www/apps/docs/content/modules/products/storefront/use-categories.mdx index b16f1ca0a5..6fbf9343b2 100644 --- a/www/apps/docs/content/modules/products/storefront/use-categories.mdx +++ b/www/apps/docs/content/modules/products/storefront/use-categories.mdx @@ -54,7 +54,7 @@ If you follow the `@medusajs/product` code blocks, it's assumed you already have ## List Categories -You can list product categories by sending a request to the [List Product Categories endpoint](https://docs.medusajs.com/api/store#product-categories_getproductcategories): +You can list product categories by sending a request to the [List Product Categories API Route](https://docs.medusajs.com/api/store#product-categories_getproductcategories): @@ -160,7 +160,7 @@ By default, the categories are not retrieved along with their nested children. T ## Get a Category by ID -You can retrieve a single product category by its ID using the [Get a Product Category endpoint](https://docs.medusajs.com/api/store#product-categories_getproductcategoriescategory): +You can retrieve a single product category by its ID using the [Get a Product Category API Route](https://docs.medusajs.com/api/store#product-categories_getproductcategoriescategory): @@ -253,7 +253,7 @@ The request returns the category as an object. On the storefront, you may use the handle of a category as its page’s path. For example, instead of displaying the category's details on the path `/categories/pcat_123`, you can display it on the path `/categories/women`, where `women` is the handle of the category. This type of URL is human-readable and is good for Search Engine Optimization (SEO) -You can retrieve the details of a category by its handle by sending a request to the List Categories endpoint, passing the `handle` as a filter: +You can retrieve the details of a category by its handle by sending a request to the List Categories API Route, passing the `handle` as a filter: diff --git a/www/apps/docs/content/modules/regions-and-currencies/admin/manage-currencies.mdx b/www/apps/docs/content/modules/regions-and-currencies/admin/manage-currencies.mdx index 154d033223..e0752c47ea 100644 --- a/www/apps/docs/content/modules/regions-and-currencies/admin/manage-currencies.mdx +++ b/www/apps/docs/content/modules/regions-and-currencies/admin/manage-currencies.mdx @@ -60,7 +60,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Currencies -You can list all available currencies in your system by sending a request to the [List Currencies endpoint](https://docs.medusajs.com/api/admin#currencies_getcurrencies): +You can list all available currencies in your system by sending a request to the [List Currencies API Route](https://docs.medusajs.com/api/admin#currencies_getcurrencies): @@ -126,7 +126,7 @@ curl -L -X GET '/admin/currencies' \ -This endpoint accepts optional filter and search query parameters. For example, you can pass the `code` query parameter to search the list of currencies by a code. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#currencies_getcurrencies). +This API Route accepts optional filter and search query parameters. For example, you can pass the `code` query parameter to search the list of currencies by a code. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#currencies_getcurrencies). This request returns an array of currencies along with pagination parameters. @@ -134,7 +134,7 @@ This request returns an array of currencies along with pagination parameters. ## Update Currencies -You can update a currency by sending a request to the [Update Currency endpoint](https://docs.medusajs.com/api/admin#currencies_postcurrenciescurrency): +You can update a currency by sending a request to the [Update Currency API Route](https://docs.medusajs.com/api/admin#currencies_postcurrenciescurrency): @@ -205,7 +205,7 @@ curl -L -X GET '/admin/currencies/' \ -This endpoint requires the currency code as a path parameter. +This API Route requires the currency code as a path parameter. In the request body parameter, it accepts the field `includes_tax` which is a boolean value that indicates whether tax inclusion is enabled for the currency. This is only available if you’ve enabled the Tax Inclusive feature. @@ -225,7 +225,7 @@ This section explains how you can manage the currencies of a store. ### List Currencies in a Store -You can list currencies in a store by sending a request to the [Get Store Details endpoint](https://docs.medusajs.com/api/admin#store_getstore): +You can list currencies in a store by sending a request to the [Get Store Details API Route](https://docs.medusajs.com/api/admin#store_getstore): @@ -303,7 +303,7 @@ This request returns the store as an object. In that object, there are two prope ### Add Currency to the Store -You can add a currency to a store using the [Add a Currency Code endpoint](https://docs.medusajs.com/api/admin#store_poststorecurrenciescode): +You can add a currency to a store using the [Add a Currency Code API Route](https://docs.medusajs.com/api/admin#store_poststorecurrenciescode): @@ -360,13 +360,13 @@ curl -L -X POST '/admin/store/currencies/' \ -This endpoint requires the currency code to be passed as a path parameter. +This API Route requires the currency code to be passed as a path parameter. The request returns the updated store as an object. You can access the new list of currencies under the `store.currencies` property. ### Delete a Currency from the Store -You can remove a currency from a store by sending a request to the [Delete Currency Code endpoint](https://docs.medusajs.com/api/admin#store_deletestorecurrenciescode): +You can remove a currency from a store by sending a request to the [Delete Currency Code API Route](https://docs.medusajs.com/api/admin#store_deletestorecurrenciescode): @@ -423,7 +423,7 @@ curl -L -X DELETE '/admin/store/currencies/' \ -This endpoint requires the currency code to be passed as a path parameter. +This API Route requires the currency code to be passed as a path parameter. The request returns the updated store as an object. You can access the new list of currencies under the `store.currencies` property. diff --git a/www/apps/docs/content/modules/regions-and-currencies/admin/manage-regions.mdx b/www/apps/docs/content/modules/regions-and-currencies/admin/manage-regions.mdx index 394fdda2c5..8171a47d6e 100644 --- a/www/apps/docs/content/modules/regions-and-currencies/admin/manage-regions.mdx +++ b/www/apps/docs/content/modules/regions-and-currencies/admin/manage-regions.mdx @@ -60,7 +60,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Regions -You can retrieve regions available on your backend using the [List Regions](https://docs.medusajs.com/api/admin#regions_getregions) endpoint: +You can retrieve regions available on your backend using the [List Regions API Route](https://docs.medusajs.com/api/admin#regions_getregions): @@ -134,7 +134,7 @@ You can also pass filters and other selection query parameters to the request. C ## Create a Region -You can create a region by sending a request to the [Create a Region](https://docs.medusajs.com/api/admin#regions_postregions) endpoint: +You can create a region by sending a request to the [Create a Region API Route](https://docs.medusajs.com/api/admin#regions_postregions): @@ -266,9 +266,9 @@ The request returns the created region in the response. ## Update a Region -You can update any of the region’s fields and configurations. The REST APIs offer different APIs for updating specific configurations, such as the [Add Country](https://docs.medusajs.com/api/admin#regions_postregionsregioncountries) endpoint. +You can update any of the region’s fields and configurations. The REST APIs offer different APIs for updating specific configurations, such as the [Add Country API Route](https://docs.medusajs.com/api/admin#regions_postregionsregioncountries). -Alternatively, you can update the details of a region using the [Update a Region](https://docs.medusajs.com/api/admin#regions_postregionsregion) endpoint: +Alternatively, you can update the details of a region using the [Update a Region API Route](https://docs.medusajs.com/api/admin#regions_postregionsregion): @@ -367,7 +367,7 @@ In the example above, the list of countries replace any countries that were prev ## Add a Shipping Option to a Region -You can add a shipping option to a region by sending a request to the [Create Shipping Option](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions) endpoint: +You can add a shipping option to a region by sending a request to the [Create Shipping Option API Route](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions): @@ -486,7 +486,7 @@ You can also manage shipping options such as list, update, and delete. You can l ## Delete a Region -You can delete a region by sending a request to the [Delete a Region](https://docs.medusajs.com/api/admin#regions_deleteregionsregion) endpoint: +You can delete a region by sending a request to the [Delete a Region API Route](https://docs.medusajs.com/api/admin#regions_deleteregionsregion): diff --git a/www/apps/docs/content/modules/regions-and-currencies/storefront/use-regions.mdx b/www/apps/docs/content/modules/regions-and-currencies/storefront/use-regions.mdx index 0f5fce1f6c..ff8db113d7 100644 --- a/www/apps/docs/content/modules/regions-and-currencies/storefront/use-regions.mdx +++ b/www/apps/docs/content/modules/regions-and-currencies/storefront/use-regions.mdx @@ -52,7 +52,7 @@ For requests that use the cart, it's also assumed you already have [used CartPro Customers should be able to see the list of available regions and select their region. -You can retrieve available regions by sending a request to the [List Regions](https://docs.medusajs.com/api/store#regions_getregions) endpoint: +You can retrieve available regions by sending a request to the [List Regions API Route](https://docs.medusajs.com/api/store#regions_getregions): @@ -119,7 +119,7 @@ When a customer selects a region, you should store that region’s ID. You’ll ## Show Product Prices Based on the Selected Region -To retrieve products with the prices based on the selected regions, you can pass the `region_id` query parameter to the [List Products](https://docs.medusajs.com/api/store#products_getproducts) or [Get a Product](https://docs.medusajs.com/api/store#products_getproductsproduct) endpoints. +To retrieve products with the prices based on the selected regions, you can pass the `region_id` query parameter to the [List Products](https://docs.medusajs.com/api/store#products_getproducts) or [Get a Product](https://docs.medusajs.com/api/store#products_getproductsproduct) API Routes. For example: @@ -176,7 +176,7 @@ fetch(`/store/products?region_id=${regionId}`, { -In this example, you send a request to the List Products endpoint, passing it the `region_id` query parameter. It is assumed that you have the ID of the region stored in the variable `regionId`. +In this example, you send a request to the List Products API Route, passing it the `region_id` query parameter. It is assumed that you have the ID of the region stored in the variable `regionId`. This request returns the list of products along with [pagination fields](https://docs.medusajs.com/api/store#pagination). The prices of the products are based on the selected region. @@ -251,6 +251,6 @@ fetch(`/store/carts/${cartId}`, { -In this example, you send a request to the [Update Cart](https://docs.medusajs.com/api/store#carts_postcartscart) endpoint. In the request’s body, you pass the parameter `region_id` and set its value to the selected region’s ID. It is assumed that you have the ID of the region stored in the variable `regionId`. +In this example, you send a request to the [Update Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscart). In the request’s body, you pass the parameter `region_id` and set its value to the selected region’s ID. It is assumed that you have the ID of the region stored in the variable `regionId`. This request returns the full object of the updated cart. \ No newline at end of file diff --git a/www/apps/docs/content/modules/sales-channels/admin/manage.mdx b/www/apps/docs/content/modules/sales-channels/admin/manage.mdx index e459637238..63f57c3586 100644 --- a/www/apps/docs/content/modules/sales-channels/admin/manage.mdx +++ b/www/apps/docs/content/modules/sales-channels/admin/manage.mdx @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## Create Sales Channels -You can create a sales channel by sending a request to the Create a Sales Channel endpoint: +You can create a sales channel by sending a request to the Create a Sales Channel API Route: @@ -135,7 +135,7 @@ It returns the created sales channel. ## List Sales Channels -You can list all sales channels by sending a request to the List Sales Channels endpoint: +You can list all sales channels by sending a request to the List Sales Channels API Route: @@ -207,7 +207,7 @@ This request returns an array of all sales channels in your store. You can also ## Retrieve a Sales Channel -You can retrieve a sales channel’s details by its ID using the Get Sales Channel endpoint: +You can retrieve a sales channel’s details by its ID using the Get Sales Channel API Route: @@ -272,7 +272,7 @@ This request returns the sales channel with the specified ID. ## Update a Sales Channel -You can update a Sales Channel’s details and attributes by sending a request to the Update Sales Channel endpoint: +You can update a Sales Channel’s details and attributes by sending a request to the Update Sales Channel API Route: @@ -355,7 +355,7 @@ You can check out [the API Reference for a full list of body parameters](https:/ ## Delete a Sales Channel -You can delete a sales channel by sending a request to the Delete Sales Channel endpoint with the ID of the sales channel to delete: +You can delete a sales channel by sending a request to the Delete Sales Channel API Route with the ID of the sales channel to delete: @@ -422,7 +422,7 @@ The ID of the deleted sales channel is returned in the response. ### Add Product to a Sales Channel -To add a product to a sales channel, send a request to the Sales Channel’s Add Products endpoint: +To add a product to a sales channel, send a request to the Sales Channel’s Add Products API Route: @@ -522,7 +522,7 @@ This request returns the sales channel. ### List Products Available in a Sales Channel -You can list the products available in a sales channel by sending a request to the List Products endpoint and passing the `sales_channel_id` query parameter to filter by a specific sales channel: +You can list the products available in a sales channel by sending a request to the List Products API Route and passing the `sales_channel_id` query parameter to filter by a specific sales channel: @@ -614,7 +614,7 @@ Deleting a product from a sales channel doesn't delete it completely. It only ma ::: -You can delete a product from a sales channel by sending a request to the Sales Channel’s Delete Products endpoint: +You can delete a product from a sales channel by sending a request to the Sales Channel’s Delete Products API Route: @@ -720,7 +720,7 @@ This request returns the sales channel. ## List Orders by Sales Channels -You can filter orders by a specific sales channel by sending a request to the List Orders endpoint and passing the `sales_channel_id` query parameter to filter by a specific sales channel: +You can filter orders by a specific sales channel by sending a request to the List Orders API Route and passing the `sales_channel_id` query parameter to filter by a specific sales channel: diff --git a/www/apps/docs/content/modules/sales-channels/storefront/use-sales-channels.mdx b/www/apps/docs/content/modules/sales-channels/storefront/use-sales-channels.mdx index 21671ff0a2..89dd86f497 100644 --- a/www/apps/docs/content/modules/sales-channels/storefront/use-sales-channels.mdx +++ b/www/apps/docs/content/modules/sales-channels/storefront/use-sales-channels.mdx @@ -53,7 +53,7 @@ For requests that use the cart, it's also assumed you already have [used CartPro ## Filter Products by Sales Channel -To filter products by a specific sales channel, pass the `sales_channel_id` query parameter to the List Products endpoint: +To filter products by a specific sales channel, pass the `sales_channel_id` query parameter to the List Products API Route: diff --git a/www/apps/docs/content/modules/taxes/admin/manage-tax-rates.mdx b/www/apps/docs/content/modules/taxes/admin/manage-tax-rates.mdx index 0155a17b7f..6720f0be42 100644 --- a/www/apps/docs/content/modules/taxes/admin/manage-tax-rates.mdx +++ b/www/apps/docs/content/modules/taxes/admin/manage-tax-rates.mdx @@ -51,7 +51,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Tax Rates -You can list the tax rates by sending a request to the [List Tax Rates endpoint](https://docs.medusajs.com/api/admin#tax-rates_gettaxrates): +You can list the tax rates by sending a request to the [List Tax Rates API Route](https://docs.medusajs.com/api/admin#tax-rates_gettaxrates): @@ -116,9 +116,9 @@ curl -L -X GET '/admin/tax-rates' \ -You can pass to this endpoint filter and search parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#tax-rates_gettaxrates). +You can pass to this API Route filter and search parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#tax-rates_gettaxrates). -The endpoint returns an array of tax rate objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). +The API Route returns an array of tax rate objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination). ### Listing Tax Rates for a Region @@ -268,7 +268,7 @@ curl -L -X GET '/admin/tax-rates?region_id[]=reg_123®ion_id[]=re ## Create Tax Rate -You can create a tax rate by sending a request to the [Create Tax Rate endpoint](https://docs.medusajs.com/api/admin#tax-rates_posttaxrates): +You can create a tax rate by sending a request to the [Create Tax Rate API Route](https://docs.medusajs.com/api/admin#tax-rates_posttaxrates): @@ -351,7 +351,7 @@ curl -L -X POST '/admin/tax-rates' \ -This endpoint requires the following body parameters: +This API Route requires the following body parameters: - `code`: a string indicating the tax code - `name`: a string indicating the name of the tax rate @@ -361,7 +361,7 @@ You can optionally pass other parameters, such as `rate`, which is a number that :::tip -You can specify here the products, product types, or shipping options that this tax rate is created for as explained in the API reference. In this guide, you’ll be using other endpoints to add or delete these conditions on a tax rate. +You can specify here the products, product types, or shipping options that this tax rate is created for as explained in the API reference. In this guide, you’ll be using other API Routes to add or delete these conditions on a tax rate. ::: @@ -371,7 +371,7 @@ The request returns the created tax rate as an object. ## Update Tax Rate -You can update a tax rate by sending a request to the [Update Tax Rate endpoint](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrate): +You can update a tax rate by sending a request to the [Update Tax Rate API Route](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrate): @@ -442,7 +442,7 @@ curl -L -X POST '/admin/tax-rates/' \ -This endpoint requires the tax rate ID to be passed as a path parameter. +This API Route requires the tax rate ID to be passed as a path parameter. In the request body, you can pass any of the tax rate’s fields as a parameter. In the example above, you pass the `name` parameter to update the name of the tax rate. Refer to the [API reference](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrate) for other parameters you can pass in the request body. @@ -456,7 +456,7 @@ This section explains how you can add and remove products from a tax rate. ### Add Product to Tax Rate -You can add a product to a tax rate by sending a request to the [Add Products endpoint](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateproducts): +You can add a product to a tax rate by sending a request to the [Add Products API Route](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateproducts): @@ -537,7 +537,7 @@ curl -L -X POST '/admin/tax-rates//products/batch' \ -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `products` parameter is required. It’s an array of strings, each string being the ID of a product to add to the tax rate. @@ -545,7 +545,7 @@ The request returns the updated tax rate as an object. You can access the tax ra ### Remove Product from Tax Rate -You can remove a product from a tax rate by sending a request to the [Delete Products endpoint](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateproducts): +You can remove a product from a tax rate by sending a request to the [Delete Products API Route](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateproducts): @@ -626,7 +626,7 @@ curl -L -X DELETE '/admin/tax-rates//products/batch' \ -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `products` parameter is required. It’s an array of strings, each string being the ID of a product to remove from the tax rate. @@ -640,7 +640,7 @@ This section explains how you can add and remove product types from a tax rate. ### Add Product Type to Tax Rate -You can add a product type to a tax rate by sending a request to the [Add Product Types endpoint](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateproducttypes): +You can add a product type to a tax rate by sending a request to the [Add Product Types API Route](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateproducttypes): @@ -725,7 +725,7 @@ curl -L -X POST '/admin/tax-rates//product-types/batch -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `product_types` parameter is required. It’s an array of strings, each string being the ID of a product type to add to the tax rate. @@ -733,7 +733,7 @@ The request returns the updated tax rate as an object. You can access the tax ra ### Remove Product Type from Tax Rate -You can remove a product type from a tax rate by sending a request to the [Delete Product Types endpoint](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateproducttypes): +You can remove a product type from a tax rate by sending a request to the [Delete Product Types API Route](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateproducttypes): @@ -818,7 +818,7 @@ curl -L -X DELETE '/admin/tax-rates//product-types/bat -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `product_types` parameter is required. It’s an array of strings, each string being the ID of a product type to remove from the tax rate. @@ -832,7 +832,7 @@ This section explains how you can add and remove shipping options from a tax rat ### Add Shipping Option to Tax Rate -You can add a shipping option to a tax rate by sending a request to the [Add Shipping Option endpoint](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateshippingoptions): +You can add a shipping option to a tax rate by sending a request to the [Add Shipping Option API Route](https://docs.medusajs.com/api/admin#tax-rates_posttaxratestaxrateshippingoptions): @@ -915,7 +915,7 @@ curl -L -X POST '/admin/tax-rates//shipping-options/ba -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `shipping_options` parameter is required. It’s an array of strings, each string being the ID of a shipping option to add to the tax rate. @@ -923,7 +923,7 @@ The request returns the updated tax rate as an object. You can access the tax ra ### Remove Shipping Options from Tax Rate -You can remove a shipping option from a tax rate by sending a request to the [Delete Shipping Options endpoint](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateshippingoptions): +You can remove a shipping option from a tax rate by sending a request to the [Delete Shipping Options API Route](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrateshippingoptions): @@ -1006,7 +1006,7 @@ curl -L -X DELETE '/admin/tax-rates//shipping-options/ -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. In the request body, the `shipping_options` parameter is required. It’s an array of strings, each string being the ID of a shipping option to remove from the tax rate. @@ -1016,7 +1016,7 @@ The request returns the updated tax rate as an object. You can access the tax ra ## Delete Tax Rate -You can delete a tax rate by sending a request to the [Delete Tax Rate endpoint](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrate): +You can delete a tax rate by sending a request to the [Delete Tax Rate API Route](https://docs.medusajs.com/api/admin#tax-rates_deletetaxratestaxrate): @@ -1073,7 +1073,7 @@ curl -L -X DELETE '/admin/tax-rates/' \ -This endpoint requires the tax rate’s ID as a path parameter. +This API Route requires the tax rate’s ID as a path parameter. The request returns the following fields: diff --git a/www/apps/docs/content/modules/taxes/admin/manage-tax-settings.mdx b/www/apps/docs/content/modules/taxes/admin/manage-tax-settings.mdx index 5b7014b45a..77efd1227c 100644 --- a/www/apps/docs/content/modules/taxes/admin/manage-tax-settings.mdx +++ b/www/apps/docs/content/modules/taxes/admin/manage-tax-settings.mdx @@ -12,7 +12,7 @@ In this document, you’ll learn how to manage tax settings using admin APIs. ## Overview -Tax settings are defined per region. You can change the tax settings of a region using the [Update Region endpoint](https://docs.medusajs.com/api/admin#regions_postregionsregion). +Tax settings are defined per region. You can change the tax settings of a region using the [Update Region API Route](https://docs.medusajs.com/api/admin#regions_postregionsregion). ### Scenario @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Tax Providers -You can list all tax providers of a store using the [List Tax Providers endpoint](https://docs.medusajs.com/api/admin#store_getstoretaxproviders): +You can list all tax providers of a store using the [List Tax Providers API Route](https://docs.medusajs.com/api/admin#store_getstoretaxproviders): @@ -120,7 +120,7 @@ curl -L -X GET '/admin/store/tax-providers' \ -This endpoint does not accept any parameters. +This API Route doesn't accept any parameters. The request returns an array of tax provider objects. @@ -128,7 +128,7 @@ The request returns an array of tax provider objects. ## Change Tax Provider of a Region -You can change the tax provider of a region using the [Update Region endpoint](https://docs.medusajs.com/api/admin#regions_postregionsregion): +You can change the tax provider of a region using the [Update Region API Route](https://docs.medusajs.com/api/admin#regions_postregionsregion): @@ -199,7 +199,7 @@ curl -L -X POST '/admin/regions/' \ -This endpoint requires the ID of the region to be passed as a path parameter. +This API Route requires the ID of the region to be passed as a path parameter. In the body of the request, you can pass any of the region’s attributes to update. To update the tax provider of a region, you can pass the `tax_provider_id` request body parameter. @@ -209,7 +209,7 @@ The request returns the updated region as an object. ## Change Tax Settings of a Region -In addition to changing the tax provider, you can use the same [Update Region endpoint](https://docs.medusajs.com/api/admin#regions_postregionsregion) to update the region’s other tax settings: +In addition to changing the tax provider, you can use the same [Update Region API Route](https://docs.medusajs.com/api/admin#regions_postregionsregion) to update the region’s other tax settings: diff --git a/www/apps/docs/content/modules/taxes/backend/create-tax-provider.md b/www/apps/docs/content/modules/taxes/backend/create-tax-provider.md index 853098ddbb..ed7a78a954 100644 --- a/www/apps/docs/content/modules/taxes/backend/create-tax-provider.md +++ b/www/apps/docs/content/modules/taxes/backend/create-tax-provider.md @@ -205,7 +205,7 @@ Run your backend to test it out: npx medusa develop ``` -Before you can test out your tax provider, you must enable it in a region. You can do that either using the [Medusa Admin dashboard](../../../user-guide/taxes/manage.md#change-tax-provider) or using the [Update Region admin endpoint](../admin/manage-tax-settings.mdx#change-tax-provider-of-a-region). +Before you can test out your tax provider, you must enable it in a region. You can do that either using the [Medusa Admin dashboard](../../../user-guide/taxes/manage.md#change-tax-provider) or using the [Update Region admin API Route](../admin/manage-tax-settings.mdx#change-tax-provider-of-a-region). Then, you can test out the tax provider by simulating a checkout process in that region. You should see the line item tax lines in the cart’s `items`, as each item object has a `tax_lines` array which are the tax lines that you return in the `getTaxLines` method for line items. diff --git a/www/apps/docs/content/modules/taxes/inclusive-pricing.md b/www/apps/docs/content/modules/taxes/inclusive-pricing.md index a1530f70bf..20406468f0 100644 --- a/www/apps/docs/content/modules/taxes/inclusive-pricing.md +++ b/www/apps/docs/content/modules/taxes/inclusive-pricing.md @@ -31,7 +31,7 @@ Then, Medusa handles calculating the tax amount using the tax rate and the tax-i Tax inclusivity can be toggled for regions, currencies, price lists, and shipping options either during creation or while editing. This is represented by the boolean attribute `includes_tax` available in the entities `Region`, `Currency`, `PriceList`, and `ShippingOption`. By default, this attribute is set to `false`. -If you want to enable or disable this attribute for any of these entities, you can use the create or update endpoints related to these entities as shown in the [Admin API reference](https://docs.medusajs.com/api/admin/). +If you want to enable or disable this attribute for any of these entities, you can use the create or update API Routes related to these entities as shown in the [Admin API reference](https://docs.medusajs.com/api/admin/). The value set for these entities can affect whether line items and shipping methods are tax inclusive or not. @@ -78,7 +78,7 @@ For example, if the tax rate is `0.25` and the price of a product is `100`, the ## Retrieving Tax Amounts -This section covers at which point tax amounts are calculated for different entities, how they are calculated when the price is tax inclusive, and what fields can be returned in the endpoints relative to each of the entities. +This section covers at which point tax amounts are calculated for different entities, how they are calculated when the price is tax inclusive, and what fields can be returned in the API Routes relative to each of the entities. :::note diff --git a/www/apps/docs/content/modules/taxes/storefront/manual-calculation.md b/www/apps/docs/content/modules/taxes/storefront/manual-calculation.md index 07a5ce5a03..328b825dd8 100644 --- a/www/apps/docs/content/modules/taxes/storefront/manual-calculation.md +++ b/www/apps/docs/content/modules/taxes/storefront/manual-calculation.md @@ -1,5 +1,4 @@ --- -description: 'Learn how to manually calculate taxes during checkout in the Medusa backend. There are different methods including using endpoints or services.' addHowToData: true --- @@ -19,9 +18,9 @@ If you disable this behavior, you must manually trigger taxes calculation. When This section explores different ways you can calculate taxes based on your purpose. -### Use Calculate Cart Taxes Endpoint +### Use Calculate Cart Taxes API Route -The [Calculate Cart Taxes](https://docs.medusajs.com/api/store#carts_postcartscarttaxes) endpoint forces the calculation of taxes for a cart during checkout. This bypasses the option set in admin to not calculate taxes automatically, which results in sending requests to the tax provider. +The [Calculate Cart Taxes](https://docs.medusajs.com/api/store#carts_postcartscarttaxes) API Route forces the calculation of taxes for a cart during checkout. This bypasses the option set in admin to not calculate taxes automatically, which results in sending requests to the tax provider. This calculates and retrieves the taxes on the cart and each of the line items in that cart. @@ -53,24 +52,30 @@ You can learn how to [retrieve and use services](../../../development/services/c Another way you can use the `CartService` to calculate taxes is using the method `decorateTotals`: -```jsx +```ts title=src/api/store/line-taxes/[cart_id]/route.ts +import { CartService } from "@medusajs/medusa" +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" -export default () => { +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + // example of retrieving cart + const cartService = req.scope.resolve( + "cartService" + ) + const cart = await cartService.retrieve(req.params.cart_id) + // ... - - router.get("/store/line-taxes", async (req, res) => { - // example of retrieving cart - const cartService = req.scope.resolve("cartService") - const cart = await cartService.retrieve(cart_id) - - // ... - // retrieve taxes of line items - const data = await decorateTotals(cart, { - force_taxes: true, - }) - - return res.status(200).json({ cart: data }) + // retrieve taxes of line items + const data = await cartService.decorateTotals(cart, { + force_taxes: true, }) + + return res.status(200).json({ cart: data }) } ``` @@ -80,7 +85,7 @@ The `decorateTotals` method accepts the cart as a first parameter and an options You can calculate and retrieve taxes of line items using the `getLineItemTotals` method available in the `TotalService` class. All you need to do is pass in the third argument to that method an options object with the key `include_tax` set to true: -```jsx +```ts const itemTotals = await totalsService .getLineItemTotals(item, cart, { include_tax: true, diff --git a/www/apps/docs/content/modules/taxes/taxes.md b/www/apps/docs/content/modules/taxes/taxes.md index 680e1df120..188cb92149 100644 --- a/www/apps/docs/content/modules/taxes/taxes.md +++ b/www/apps/docs/content/modules/taxes/taxes.md @@ -14,7 +14,7 @@ In Medusa, there are different ways you can customize taxes, allowing you to imp - Create a tax provider that defines the tax lines applied to line items and shipping methods. - Customize the tax calculation strategy to change how taxes are calculated. -- Override tax rates for specific products, product types, or shipping options in a region using endpoints or services. +- Override tax rates for specific products, product types, or shipping options in a region using API Routes or services. --- diff --git a/www/apps/docs/content/modules/users/admin/manage-invites.mdx b/www/apps/docs/content/modules/users/admin/manage-invites.mdx index 7ff07ed8b6..36ad528584 100644 --- a/www/apps/docs/content/modules/users/admin/manage-invites.mdx +++ b/www/apps/docs/content/modules/users/admin/manage-invites.mdx @@ -46,7 +46,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus ### Authenticated Admin User -Except for the Accept Invite endpoint, you must be an authenticated admin user before following along with the steps in the tutorial. +Except for the Accept Invite API Route, you must be an authenticated admin user before following along with the steps in the tutorial. You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin#authentication). @@ -54,7 +54,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Invites -You can list invites by sending a request to the [List Invite endpoint](https://docs.medusajs.com/api/admin#invites_getinvites): +You can list invites by sending a request to the [List Invite API Route](https://docs.medusajs.com/api/admin#invites_getinvites): @@ -117,15 +117,15 @@ curl -L -X GET '/admin/invites' \ -This endpoint does not accept any parameters. +This API Route doesn't accept any parameters. -The request returns an array of invite endpoints. +The request returns an array of invite objects. --- ## Create Invite -You can create an invite by sending a request to the [Create Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvites): +You can create an invite by sending a request to the [Create Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvites): @@ -200,7 +200,7 @@ curl -L -X POST '/admin/invites' \ -This endpoint requires the following body parameters: +This API Route requires the following body parameters: - `user`: a string indicating the email of the user. - `role`: a string indicating the role of the user. Its values can be `admin`, `member`, and `developer`. @@ -213,7 +213,7 @@ The request does not return any data. If the invite was created successfully, th A logged-out user can accept an invite, which would create a user for that user. -You can accept an invite by sending a request to the [Accept Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept): +You can accept an invite by sending a request to the [Accept Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept): @@ -303,7 +303,7 @@ curl -L -X POST '/admin/invites/accept' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `token`: a string indicating the invitation’s token. - `user`: an object that has the following properties: @@ -317,7 +317,7 @@ The request does not return any data. If the invite was accepted successfully, t ## Resend an Invite -You can resend an invite if it’s not accepted yet. To resend an invite, send a request to the [Resend Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteresend): +You can resend an invite if it’s not accepted yet. To resend an invite, send a request to the [Resend Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvitesinviteresend): @@ -374,15 +374,15 @@ curl -L -X POST '/admin/invites//resend' \ -This endpoint requires the invite ID as a path parameter. +This API Route requires the invite ID as a path parameter. -The request does not return any data. If the invite was resent successfully, the status code of the response will be `200`. +The request doesn't return any data. If the invite was resent successfully, the status code of the response will be `200`. --- ## Delete an Invite -You can delete an invite by sending a request to the [Delete Invite endpoint](https://docs.medusajs.com/api/admin#invites_deleteinvitesinvite): +You can delete an invite by sending a request to the [Delete Invite API Route](https://docs.medusajs.com/api/admin#invites_deleteinvitesinvite): @@ -439,7 +439,7 @@ curl -L -X DELETE '/admin/invites/' \ -This endpoint requires the invite ID as a path parameter. +This API Route requires the invite ID as a path parameter. It deletes the invite and returns the following fields: diff --git a/www/apps/docs/content/modules/users/admin/manage-profile.mdx b/www/apps/docs/content/modules/users/admin/manage-profile.mdx index 72d4a4e5b9..c2700386da 100644 --- a/www/apps/docs/content/modules/users/admin/manage-profile.mdx +++ b/www/apps/docs/content/modules/users/admin/manage-profile.mdx @@ -42,7 +42,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus ### Authenticated Admin User -Aside from the User Login and Reset Password steps, other endpoints require you to be an authenticated admin user. +Aside from the User Login and Reset Password steps, other API Routes require you to be an authenticated admin user. You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin#authentication). @@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ### User Login -You can log in a user by sending a request to the [User Login endpoint](https://docs.medusajs.com/api/admin#auth_postauth): +You can log in a user by sending a request to the [User Login API Route](https://docs.medusajs.com/api/admin#auth_postauth): @@ -126,7 +126,7 @@ curl -L -X POST '/admin/auth' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `email`: a string indicating the user’s email. - `password`: a string indicating the user’s password. @@ -135,7 +135,7 @@ The request returns the logged-in user as an object. ### User Logout -You can log out a user by sending a request to the [User Logout endpoint](https://docs.medusajs.com/api/admin#auth_deleteauth): +You can log out a user by sending a request to the [User Logout API Route](https://docs.medusajs.com/api/admin#auth_deleteauth): @@ -192,15 +192,15 @@ curl -L -X DELETE '/admin/auth' \ -The endpoint does not require any path or query parameters. +The API Route doesn't require any path or query parameters. -The request does not return any data. The response code will be `200` for successful log out. +The request doesn't return any data. The response code will be `200` for successful log out. --- ## Retrieve User Profile Details -You can retrieve the current user’s details for their profile by sending a request to the [Get Current User endpoint](https://docs.medusajs.com/api/admin#auth_getauth): +You can retrieve the current user’s details for their profile by sending a request to the [Get Current User API Route](https://docs.medusajs.com/api/admin#auth_getauth): @@ -256,7 +256,7 @@ curl -L -X GET '/admin/auth' \ -This endpoint does not require any parameters. +This API Route doesn't require any parameters. The request returns the current user as an object. @@ -264,7 +264,7 @@ The request returns the current user as an object. ## Update User’s Profile Details -You can update a user’s details in their profile by sending a request to the [Update User endpoint](https://docs.medusajs.com/api/admin#users_postusersuser): +You can update a user’s details in their profile by sending a request to the [Update User API Route](https://docs.medusajs.com/api/admin#users_postusersuser): @@ -338,7 +338,7 @@ curl -L -X POST '/admin/users/' \ -This endpoint requires the ID of the user as a path parameter. +This API Route requires the ID of the user as a path parameter. In the request body, you can pass any of the user’s fields that you want to update as a parameter. In the example above, you pass the `first_name` parameter to update the user’s first name. You can refer to the [API reference](https://docs.medusajs.com/api/admin#users_postusersuser) to learn about other available parameters. @@ -360,7 +360,7 @@ Sending the password reset email is not handled by default in the Medusa backend ::: -You can request a password reset by sending a request to the [Request Password Reset endpoint](https://docs.medusajs.com/api/admin#users_postusersuserpasswordtoken): +You can request a password reset by sending a request to the [Request Password Reset API Route](https://docs.medusajs.com/api/admin#users_postusersuserpasswordtoken): @@ -430,7 +430,7 @@ curl -L -X POST '/admin/users/password-token' \ -This endpoint requires the `email` parameter in the request body, which is the email of the user requesting to reset their password. +This API Route requires the `email` parameter in the request body, which is the email of the user requesting to reset their password. The request does not return any data. The response code will be `204` if the request was processed successfully. @@ -438,7 +438,7 @@ The request does not return any data. The response code will be `204` if the req After the user resets their password and, typically, receives an email with a link to reset their password, they should enter their new password. The new password, along with the token passed to this page are used to reset the password on the Medusa backend. -You can reset the password by sending a request to the [Reset Password endpoint](https://docs.medusajs.com/api/admin#users_postusersuserpassword): +You can reset the password by sending a request to the [Reset Password API Route](https://docs.medusajs.com/api/admin#users_postusersuserpassword): @@ -512,7 +512,7 @@ curl -L -X POST '/admin/users/reset-password' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `token`: a string indicating the password reset token. - `password`: a string indicating the new password for the user. diff --git a/www/apps/docs/content/modules/users/admin/manage-users.mdx b/www/apps/docs/content/modules/users/admin/manage-users.mdx index ae6745e597..e113cfacc8 100644 --- a/www/apps/docs/content/modules/users/admin/manage-users.mdx +++ b/www/apps/docs/content/modules/users/admin/manage-users.mdx @@ -53,7 +53,7 @@ You can learn more about [authenticating as an admin user in the API reference]( ## List Users -You can retrieve users in a store by sending a request to the [List Users endpoint](https://docs.medusajs.com/api/admin#users_getusers): +You can retrieve users in a store by sending a request to the [List Users API Route](https://docs.medusajs.com/api/admin#users_getusers): @@ -116,7 +116,7 @@ curl -L -X GET '/admin/users' \ -This endpoint does not require any parameters. +This API Route doesn't require any parameters. The request returns an array of user objects. @@ -124,7 +124,7 @@ The request returns an array of user objects. ## Create a User -You can create a user by sending a request to the [Create User endpoint](https://docs.medusajs.com/api/admin#users_postusers): +You can create a user by sending a request to the [Create User API Route](https://docs.medusajs.com/api/admin#users_postusers): @@ -199,12 +199,12 @@ curl -L -X POST '/admin/users' \ -This endpoint requires the following request body parameters: +This API Route requires the following request body parameters: - `email`: a string indicating the email of the user. - `password`: a string indicating the password of the user. -The endpoint accepts other optional body parameters, such as first name or last name. Check the [API reference](https://docs.medusajs.com/api/admin#users_postusers) for details on optional body parameters. +The API Route accepts other optional body parameters, such as first name or last name. Check the [API reference](https://docs.medusajs.com/api/admin#users_postusers) for details on optional body parameters. The request returns the created user as an object. @@ -212,7 +212,7 @@ The request returns the created user as an object. ## Update User -You can update a user’s details by sending a request to the [Update User endpoint](https://docs.medusajs.com/api/admin#users_postusersuser): +You can update a user’s details by sending a request to the [Update User API Route](https://docs.medusajs.com/api/admin#users_postusersuser): @@ -283,7 +283,7 @@ curl -L -X POST '/admin/users/' \ -This endpoint requires the ID of the user as a path parameter. +This API Route requires the ID of the user as a path parameter. In the request body, you can pass any of the user’s fields that you want to update as parameters. In the example above, you update the user’s `first_name`. Check the [API reference](https://docs.medusajs.com/api/admin#users_postusersuser) for all the optional parameters. @@ -293,7 +293,7 @@ The request returns the updated user as an object. ## Delete a User -You can delete a user by sending a request to the [Delete User endpoint](https://docs.medusajs.com/api/admin#users_deleteusersuser): +You can delete a user by sending a request to the [Delete User API Route](https://docs.medusajs.com/api/admin#users_deleteusersuser): @@ -350,7 +350,7 @@ curl -L -X DELETE '/admin/users/' \ -This endpoint requires the user ID as a path parameter. +This API Route requires the user ID as a path parameter. It deletes the user and returns the following fields: diff --git a/www/apps/docs/content/modules/users/backend/rbac.mdx b/www/apps/docs/content/modules/users/backend/rbac.mdx index d1278c5d59..a83bafaa8d 100644 --- a/www/apps/docs/content/modules/users/backend/rbac.mdx +++ b/www/apps/docs/content/modules/users/backend/rbac.mdx @@ -333,13 +333,13 @@ This will reflect the entity changes in your database. ## Create Guard Middleware -To ensure that users who have the privilege can access an endpoint, you must create a middleware that guards admin routes. This middleware will run on all authenticated admin requests to ensure that only allowed users can access an endpoint. +To ensure that users who have the privilege can access an API Route, you must create a middleware that guards admin routes. This middleware will run on all authenticated admin requests to ensure that only allowed users can access an API Route. Since the Medusa backend uses Express, you can create a middleware and attach it to all admin routes. Example Implementation -In this example, you’ll create a middleware that runs on all admin-authenticated routes and checks the logged-in user’s permissions before giving them access to an endpoint. +In this example, you’ll create a middleware that runs on all admin-authenticated routes and checks the logged-in user’s permissions before giving them access to an API Route. -Create the file `src/api/middlewares/permission.ts` with the following content: +Create the file `src/api/middlewares.ts` with the following content: -```ts title=src/api/middlewares/permission.ts -import { UserService } from "@medusajs/medusa" -import { NextFunction, Request, Response } from "express" +```ts title=src/api/middlewares.ts +import type { + MiddlewaresConfig, + UserService, +} from "@medusajs/medusa" +import express from "express" +import type { + MedusaRequest, + MedusaResponse, + MedusaNextFunction, +} from "@medusajs/medusa" -export default async ( - req: Request, - res: Response, - next: NextFunction +export const permissions = async ( + req: MedusaRequest, + res: MedusaResponse, + next: MedusaNextFunction ) => { if (!req.user || !req.user.userId) { next() @@ -406,48 +414,38 @@ export default async ( // deny access res.sendStatus(401) } + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/admin/*", + middlewares: [permissions], + }, + ], +} ``` -In this middleware, you ensure that there is a logged-in user and the logged-in user has a role. If not, the user is admitted to access the endpoint. Here, you presume that logged-in users who don’t have a role are “super-admin” users who can access all endpoints. You may choose to implement this differently. +In this middleware, you ensure that there is a logged-in user and the logged-in user has a role. If not, the user is admitted to access the API Route. Here, you presume that logged-in users who don’t have a role are “super-admin” users who can access all API Routes. You may choose to implement this differently. -If there’s a logged-in user that has a role, you check that the role’s permissions give them access to the current endpoint. You do that by checking if a permission’s metadata has a key with the same request’s path. It may be better here to check for matching using regular expressions, for example, to check routes with path parameters. +If there’s a logged-in user that has a role, you check that the role’s permissions give them access to the current API Route. You do that by checking if a permission’s metadata has a key with the same request’s path. It may be better here to check for matching using regular expressions, for example, to check routes with path parameters. Otherwise, if the user’s role doesn’t provide them with enough permissions, you return a `401` response code. :::tip -Notice that you use `req.path` here to get the current endpoint path. However, in middlewares, this doesn’t include the mount point which is `/admin`. So, for example, if the endpoint path is `/admin/products`, `req.path` will be `/products`. You can alternatively use `req.originalUrl`. Learn more in [Express’s documentation](https://expressjs.com/en/api.html#req.originalUrl). +Notice that you use `req.path` here to get the current API Route path. However, in middlewares, this doesn’t include the mount point which is `/admin`. So, for example, if the API Route path is `/admin/products`, `req.path` will be `/products`. You can alternatively use `req.originalUrl`. Learn more in [Express’s documentation](https://expressjs.com/en/api.html#req.originalUrl). ::: -Next, to ensure that this middleware is used, import it in `src/api/index.ts` and apply it on admin routes: - -```ts title=src/api/index.ts -import permissionMiddleware from "./middlewares/permission" - -export default (rootDirectory: string): Router | Router[] => { - // ... - const router = Router() - // ... - - // use middleware on admin routes - router.use("/admin", permissionMiddleware) - - return router -} -``` - -This assumes you already have a router with all necessary CORS configurations and body parsing middlewares. If not, you can refer to the [Create Endpoint documentation](../../../development/endpoints/create.mdx) for more details. - -Make sure to use the permission middleware after all router configurations if you want the middleware to work on your custom admin routes. +After defining the middleware, you apply it on all API Routes starting with `/admin/`. --- -## Create Endpoints and Services +## Create API Routes and Services -To manage the roles and permissions, you’ll need to create custom endpoints, typically for Create, Read, Update, and Delete (CRUD) operations. +To manage the roles and permissions, you’ll need to create custom API Routes, typically for Create, Read, Update, and Delete (CRUD) operations. You’ll also need to create a service for each of `Role` and `Permission` entities to perform these operations on them. The entity uses the service within its code. @@ -456,11 +454,11 @@ Furthermore, you may need to extend core services if you need to perform actions -In this example, you’ll only implement two endpoints for simplicity: create role endpoint that create a new role with permissions, and associate user endpoint that associates a user with a role. +In this example, you’ll only implement two API Routes for simplicity: create role API Route that create a new role with permissions, and associate user API Route that associates a user with a role. -You’ll also create basic services for `Role` and `Permission` to perform the functionalities of each of these endpoints and extend the core `UserService` to allow associating roles with users. +You’ll also create basic services for `Role` and `Permission` to perform the functionalities of each of these API Routes and extend the core `UserService` to allow associating roles with users. Start by creating the file `src/services/permission.ts` with the following content: @@ -663,15 +661,21 @@ This creates the `RoleService` with three methods: - `create`: Creates a new role and, if provided, its permissions as well. - `associateUser`: associates a user with a role. -Now, you can create the endpoints. +Now, you can create the API Routes. -Start by creating the file `src/api/routes/admin/role/create-role.ts` with the following content: +Start by creating the file `src/api/admin/roles/route.ts` with the following content: -```ts title=src/api/routes/admin/role/create-role.ts -import { Request, Response } from "express" +```ts title=src/api/admin/roles/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import RoleService from "../../../../services/role" -export default async (req: Request, res: Response) => { +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // omitting validation for simplicity const { name, @@ -693,15 +697,21 @@ export default async (req: Request, res: Response) => { } ``` -This creates the Create Role endpoint that uses the `RoleService` to create a new role. Notice that validation of received body parameters is omitted for simplicity. +This creates the Create Role API Route at `/admin/roles` that uses the `RoleService` to create a new role. Notice that validation of received body parameters is omitted for simplicity. -Next, create the file `src/api/routes/admin/role/associate-user.ts` with the following content: +Next, create the file `src/api/routes/admin/roles/[id]/user/[user_id]/route.ts` with the following content: -```ts title=src/api/routes/admin/role/associate-user.ts -import { Request, Response } from "express" +```ts title=src/api/routes/admin/roles/[id]/user/[user_id]/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import RoleService from "../../../../services/role" -export default async (req: Request, res: Response) => { +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // omitting validation for simplicity purposes const { id, @@ -717,44 +727,9 @@ export default async (req: Request, res: Response) => { } ``` -This creates the Associate User endpoint that uses the `RoleService` to associate a role with a user. +This creates the Associate User API Route at `/admin/roles/[id]/user/[user_id]` that uses the `RoleService` to associate a role with a user. -You now have to register and export these endpoints. - -To do that, create the file `src/api/routes/admin/role/index.ts` with the following content: - -```ts title=src/api/routes/admin/role/index.ts -import { wrapHandler } from "@medusajs/utils" -import { Router } from "express" -import createRole from "./create-role" -import associateUser from "./associate-user" - -const router = Router() - -export default (adminRouter: Router) => { - adminRouter.use("/roles", router) - - router.post("/", wrapHandler(createRole)) - router.post("/:id/user/:user_id", wrapHandler(associateUser)) -} -``` - -This adds the create role endpoint under the path `/admin/roles`, and the associate user endpoint under the path `/admin/roles/:id/user/:user_id`, where `:id` is the ID of the role and `:user_id` is the ID of the user to associate with the role. - -Finally, you can either export these routes in `src/api/routes/admin/index.ts` or, if the file is not available in your project, in `src/api/index.ts`: - -```ts title=src/api/routes/admin/index.ts -import roleRouter from "./role" - -const router = Router() - -export function attachAdminRoutes(adminRouter: Router) { - roleRouter(adminRouter) - // .... -} -``` - -To test it out, run the `build` command in the root directory of your Medusa backend project: +To test the API Routes out, run the `build` command in the root directory of your Medusa backend project: ```bash npm2yarn npm run build @@ -766,30 +741,30 @@ Then, start the backend with the following command: npx medusa develop ``` -Try first to log in using the [Admin User Login endpoint](https://docs.medusajs.com/api/admin#auth_postauth) with an existing admin user. Then, send a `POST` request to the `localhost:9000/admin/roles` endpoint with the following request body parameters: +Try first to log in using the [Admin User Login API Route](https://docs.medusajs.com/api/admin#auth_postauth) with an existing admin user. Then, send a `POST` request to the `localhost:9000/admin/roles` API Route with the following request body parameters: ```json { - "store_id": "store_01H8XPDY8WA1Z650MZSEY4Y0V0", - "name": "Product Manager", - "permissions": [ - { - "name": "Allow Products", - "metadata": { - "/products": true - } - } - ] + "store_id": "store_01H8XPDY8WA1Z650MZSEY4Y0V0", + "name": "Product Manager", + "permissions": [ + { + "name": "Allow Products", + "metadata": { + "/products": true + } + } + ] } ``` -Make sure to replace the `store_id`'s value with your store’s ID. You can retrieve the store’s ID using the [Get Store Details endpoint](https://docs.medusajs.com/api/admin#store_getstore). +Make sure to replace the `store_id`'s value with your store’s ID. You can retrieve the store’s ID using the [Get Store Details API Route](https://docs.medusajs.com/api/admin#store_getstore). -This will create a new role with a permission that allows users of this role to access the `/admin/products` endpoint. As mentioned before, because of the middleware’s implementation, you must specify the path without the `/admin` prefix. If you chose to implement this differently, such as with regular expressions, then change the permission’s metadata accordingly. +This will create a new role with a permission that allows users of this role to access the `/admin/products` API Route. As mentioned before, because of the middleware’s implementation, you must specify the path without the `/admin` prefix. If you chose to implement this differently, such as with regular expressions, then change the permission’s metadata accordingly. -Next, create a new user using the [Create User endpoint](https://docs.medusajs.com/api/admin#users_postusers). Then, send a `POST` request to `localhost:9000/admin/roles//user/`, where `` is the ID of the role you created, and `` is the ID of the user you created. This will associate the user with the role you created. +Next, create a new user using the [Create User API Route](https://docs.medusajs.com/api/admin#users_postusers). Then, send a `POST` request to `localhost:9000/admin/roles//user/`, where `` is the ID of the role you created, and `` is the ID of the user you created. This will associate the user with the role you created. -Finally, login with the user you created, then try to access any endpoint other than `/admin/products`. You’ll receive a `401` unauthorized response. Then, try to access the [List Products endpoint](https://docs.medusajs.com/api/admin#products_getproducts), and the user should be able to access it as expected. +Finally, login with the user you created, then try to access any API Route other than `/admin/products`. You’ll receive a `401` unauthorized response. Then, try to access the [List Products API Route](https://docs.medusajs.com/api/admin#products_getproducts), and the user should be able to access it as expected. diff --git a/www/apps/docs/content/modules/users/users.md b/www/apps/docs/content/modules/users/users.md index afb3f33724..51e7ffa29e 100644 --- a/www/apps/docs/content/modules/users/users.md +++ b/www/apps/docs/content/modules/users/users.md @@ -26,7 +26,7 @@ Some of the `User` entity attributes include: - `password_hash`: a string indicating the encrypted password of the user. Passwords are encrypted using the [scrypt-kdf NPM package](https://www.npmjs.com/package/scrypt-kdf). The password hash is nullable, which can be useful if you want to integrate a third-party authentication service that does not require a password. - `first_name`: a string indicating the user’s first name. - `last_name`: a string indicating the user’s last name. -- `api_token`: a string that holds the user’s API token. The API token can be used to send authenticated requests to admin endpoints, instead of using cookie session authentication. Check out the [API reference](https://docs.medusajs.com/api/admin#authentication) to learn how to use it. +- `api_token`: a string that holds the user’s API token. The API token can be used to send authenticated requests to admin API Routes, instead of using cookie session authentication. Check out the [API reference](https://docs.medusajs.com/api/admin#authentication) to learn how to use it. - `role`: a string that indicates the role of the user. Its value can be either `admin`, `member`, or `developer`. :::note @@ -61,11 +61,11 @@ You have full freedom in how you choose to implement the invite flow. This secti The invitation process typically follows these steps in the Medusa backend: -1. A user creates an invite either using the [Create Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvites) or the `InviteService`'s `create` method. Part of creating an invite includes generating the token and setting the expiry date. By default, the expiry date is set to a week after the date of invitation creation. -2. The new user receives the invite, typically through their email (although this is not implemented by default within the Medusa backend). The new user has to provide their details and password. The invite can be accepted either using the [Accept Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept) or using the `InviteService`'s `accept` method. +1. A user creates an invite either using the [Create Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvites) or the `InviteService`'s `create` method. Part of creating an invite includes generating the token and setting the expiry date. By default, the expiry date is set to a week after the date of invitation creation. +2. The new user receives the invite, typically through their email (although this is not implemented by default within the Medusa backend). The new user has to provide their details and password. The invite can be accepted either using the [Accept Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept) or using the `InviteService`'s `accept` method. 3. When the new user accepts the invite, the invitation is validated first to ensure it’s not expired. If it’s not expired, a new user is created using the `UserService`'s [create method](../../references/services/classes/UserService.md#create). -If an invitation is expired, an existing user can resend the invite either using the Resend Invite endpoint or using the `InviteService`'s resend method. This would generate a new token and reset the expiry date. +If an invitation is expired, an existing user can resend the invite either using the Resend Invite API Route or using the `InviteService`'s resend method. This would generate a new token and reset the expiry date. --- diff --git a/www/apps/docs/content/plugins/analytics/segment.md b/www/apps/docs/content/plugins/analytics/segment.md index b44df00732..4f9c44f666 100644 --- a/www/apps/docs/content/plugins/analytics/segment.md +++ b/www/apps/docs/content/plugins/analytics/segment.md @@ -185,7 +185,7 @@ You resolve the `SegmentService` using dependency injection. Then, when the `cus :::info -Services can be resolved and used in Subscribers, endpoints, and other Services. Learn [how to resolve services in the Services documentation](../../development/services/create-service.mdx#using-your-custom-service). +Services can be resolved and used in Subscribers, API Routes, and other Services. Learn [how to resolve services in the Services documentation](../../development/services/create-service.mdx#using-your-custom-service). ::: diff --git a/www/apps/docs/content/plugins/file-service/local.md b/www/apps/docs/content/plugins/file-service/local.md index 286d82d388..80a331b361 100644 --- a/www/apps/docs/content/plugins/file-service/local.md +++ b/www/apps/docs/content/plugins/file-service/local.md @@ -80,7 +80,7 @@ If this configuration is not added, you’ll receive the error ["next/image Un-c In `next.config.js` add the following option in the exported object: -```jsx title=next.config.js +```js title=next.config.js const { withStoreConfig } = require("./store-config") // ... diff --git a/www/apps/docs/content/plugins/notifications/mailchimp.md b/www/apps/docs/content/plugins/notifications/mailchimp.md index 9308fe57e1..6dc5197d7a 100644 --- a/www/apps/docs/content/plugins/notifications/mailchimp.md +++ b/www/apps/docs/content/plugins/notifications/mailchimp.md @@ -80,7 +80,7 @@ const plugins = [ ## Test it Out -This plugin adds new `POST` and `PUT` endpoints at `/mailchimp/subscribe`. These endpoints require in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp. You can check out [Mailchimp’s subscription documentation](https://mailchimp.com/developer/marketing/api/list-merges/) for more details on the data you can send. +This plugin adds new `POST` and `PUT` API Routes at `/mailchimp/subscribe`. These API Routes require in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp. You can check out [Mailchimp’s subscription documentation](https://mailchimp.com/developer/marketing/api/list-merges/) for more details on the data you can send. ### Without Additional Data @@ -92,7 +92,7 @@ Try sending a `POST` or `PUT` request to `/mailchimp/subscribe` with the followi } ``` -If the subscription is successful, a `200` response code will be returned with `OK` message. If the same email address is used again in the `POST`, a `400` response will be returned with an error page. If this can occur in your usecase, use the `PUT` endpoint to prevent this. +If the subscription is successful, a `200` response code will be returned with `OK` message. If the same email address is used again in the `POST`, a `400` response will be returned with an error page. If this can occur in your usecase, use the `PUT` API Route to prevent this. ![Postman](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000185/Medusa%20Docs/Mailchimp/tpr7uCF_g4rymn.png) @@ -119,22 +119,34 @@ All fields inside `data` will be sent to Mailchimp’s API along with the email. ## Use Mailchimp Service -If you want to subscribe to users without using this endpoint or at a specific place in your code, you can use Mailchimp’s service `mailchimpService` in your endpoints, services, or subscribers. This service has a method `subscribeNewsletter` which lets you use the subscribe functionality. +To subscribe users to the newsletter without using this API Route or at a specific place in your code, you can use Mailchimp’s service `mailchimpService` in your API Routes, services, or subscribers. This service has a method `subscribeNewsletter` which lets you use the subscribe functionality. -Here’s an example of using the `mailchimpService` inside an endpoint: +Here’s an example of using the `mailchimpService` in an API Route: -```jsx title=src/api/index.ts -const mailchimpService = req.scope.resolve("mailchimpService") +```ts title=src/api/store/subscribe/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" -mailchimpService.subscribeNewsletter( - "example@gmail.com", - { tags: ["customer"] } // optional -) +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const mailchimpService = req.scope.resolve( + "mailchimpService" + ) + + mailchimpService.subscribeNewsletter( + "example@gmail.com", + { tags: ["customer"] } // optional + ) +} ``` :::tip -You can learn more about how you can use services in your endpoints, services, and subscribers in the [Services documentation](../../development/services/create-service.mdx#using-your-custom-service). +You can learn more about how you can use services in your API Routes, services, and subscribers in the [Services documentation](../../development/services/create-service.mdx#using-your-custom-service). ::: diff --git a/www/apps/docs/content/plugins/notifications/sendgrid.mdx b/www/apps/docs/content/plugins/notifications/sendgrid.mdx index c85e816993..f9246d11ac 100644 --- a/www/apps/docs/content/plugins/notifications/sendgrid.mdx +++ b/www/apps/docs/content/plugins/notifications/sendgrid.mdx @@ -3930,7 +3930,7 @@ Where `", - to: "customer@mail.com", - dynamic_template_data: { dynamic: "data" }, - } +For example, in an API Route: -sendgridService.sendEmail(sendOptions) +```ts title=src/api/store/email/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" + +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const sendgridService = req.scope.resolve("sendgridService") + const sendOptions = { + templateId: "d-123....", + from: "ACME ", + to: "customer@mail.com", + dynamic_template_data: { dynamic: "data" }, + } + + sendgridService.sendEmail(sendOptions) +} ``` --- diff --git a/www/apps/docs/content/plugins/notifications/slack.md b/www/apps/docs/content/plugins/notifications/slack.md index a89b46f8a0..1b93b29ad4 100644 --- a/www/apps/docs/content/plugins/notifications/slack.md +++ b/www/apps/docs/content/plugins/notifications/slack.md @@ -78,7 +78,7 @@ npm install medusa-plugin-slack-notification After that, open `medusa-config.js` and add the new plugin with its configurations in the `plugins` array: -```jsx title=medusa-config.js +```js title=medusa-config.js const plugins = [ // ..., { diff --git a/www/apps/docs/content/plugins/notifications/twilio-sms.md b/www/apps/docs/content/plugins/notifications/twilio-sms.md index edf997b752..a46eddb6db 100644 --- a/www/apps/docs/content/plugins/notifications/twilio-sms.md +++ b/www/apps/docs/content/plugins/notifications/twilio-sms.md @@ -55,7 +55,7 @@ Make sure to replace ``, ``, and ` { - const router = Router() +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + // skipping validation for simplicity + const { dynamicCode } = req.body + const discountGenerator = req.scope.resolve( + "discountGeneratorService" + ) + const code = await discountGenerator.generateDiscount( + dynamicCode + ) - router.use( - "/generate-discount-code", - bodyParser.json(), - async (req: Request, res: Response) => { - // skipping validation for simplicity - const { dynamicCode } = req.body - const discountGenerator = req.scope.resolve( - "discountGeneratorService" - ) - const code = await discountGenerator.generateDiscount( - dynamicCode - ) - - res.json({ - code, - }) + res.json({ + code, }) - - return router } -``` \ No newline at end of file +``` diff --git a/www/apps/docs/content/plugins/other/ip-lookup.md b/www/apps/docs/content/plugins/other/ip-lookup.md index 578227a943..a01f60d620 100644 --- a/www/apps/docs/content/plugins/other/ip-lookup.md +++ b/www/apps/docs/content/plugins/other/ip-lookup.md @@ -70,74 +70,72 @@ Due to how Express resolves the current IP when accessing your website from `loc ### IpLookupService -The `IpLookupService` can be used in other services, endpoints, or resources to get the user’s location by their IP address. It has only one method `lookupIp` that accepts the IP address as a parameter, sends a request to ipstack’s API, and returns the retrieved result. +The `IpLookupService` can be used in other services, API Routes, or resources to get the user’s location by their IP address. It has only one method `lookupIp` that accepts the IP address as a parameter, sends a request to ipstack’s API, and returns the retrieved result. -For example, you can use the `IpLookupService` in a custom endpoint and return the user’s region: +For example, you can use the `IpLookupService` in a custom API Route and return the user’s region: :::tip -You can learn more about creating an endpoint [here](../../development/endpoints/create.mdx). +You can learn more about creating an API Route [here](../../development/api-routes/create.mdx). ::: -```ts title=src/api/index.ts -import { Request, Response, Router } from "express" +```ts title=src/api/store/customer-region/route.ts +import type { + MedusaRequest, + MedusaResponse, + RegionService, +} from "@medusajs/medusa" -export default (rootDirectory: string): Router | Router[] => { - const router = Router() - // ... - router.get( - "/store/customer-region", - async (req: Request, res: Response) => { - const ipLookupService = req.scope.resolve( - "ipLookupService" - ) - const regionService = req.scope.resolve( - "regionService" - ) - - const ip = req.headers["x-forwarded-for"] || - req.socket.remoteAddress - - const { data } = await ipLookupService.lookupIp(ip) - - if (!data.country_code) { - throw new Error ("Couldn't detect country code.") - } - - const region = await regionService - .retrieveByCountryCode(data.country_code) - - res.json({ - region, - }) - } +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const ipLookupService = req.scope.resolve( + "ipLookupService" ) + const regionService = req.scope.resolve( + "regionService" + ) + + const ip = req.headers["x-forwarded-for"] || + req.socket.remoteAddress + + const { data } = await ipLookupService.lookupIp(ip) + + if (!data.country_code) { + throw new Error ("Couldn't detect country code.") + } + + const region = await regionService + .retrieveByCountryCode(data.country_code) + + res.json({ + region, + }) } ``` ### preCartCreation -The `preCartCreation` middleware can be added as a middleware to any route to attach the region ID to that route based on the user’s location. For example, you can use it on the Create Cart endpoint to ensure that the user’s correct region is attached to the cart. +The `preCartCreation` middleware can be added as a middleware to any route to attach the region ID to that route based on the user’s location. For example, you can use it on the Create Cart API Route to ensure that the user’s correct region is attached to the cart. For example, you can attach it to all `/store` routes to ensure the customer’s region is always detected: -```ts title=src/api/index.ts -import { Router } from "express" - +```ts title=src/api/middlewares.ts +import type { MiddlewaresConfig } from "@medusajs/medusa" const { preCartCreation } = require( "medusa-plugin-ip-lookup/api/medusa-middleware" ).default -export default ( - rootDirectory: string -): Router | Router[] => { - const router = Router() - // ... - router.use("/store", preCartCreation) - - return router +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/*", + middlewares: [preCartCreation], + }, + ], } ``` diff --git a/www/apps/docs/content/plugins/other/restock-notifications.md b/www/apps/docs/content/plugins/other/restock-notifications.md index c95bd768ea..dff2e47dfd 100644 --- a/www/apps/docs/content/plugins/other/restock-notifications.md +++ b/www/apps/docs/content/plugins/other/restock-notifications.md @@ -16,7 +16,7 @@ This plugin doesn't actually implement the sending of the notification, only the Customers browsing your products may find something that they need, but it's unfortunately out of stock. In this scenario, you can keep them interested in your product and, subsequently, in your store by notifying them when the product is back in stock. -The Restock Notifications plugin provides new endpoints that allow the customer to subscribe to restock notifications of a specific product variant. It also triggers the `restock-notification.restocked` event whenever a product variant's stock quantity is above a specified threshold. The event's payload includes the ID of the product variant and the customer emails subscribed to it. You can pair this with a subscriber that listens to that event and sends a notification to the customer using a [Notification plugin](../notifications/). +The Restock Notifications plugin provides new API Routes that allow the customer to subscribe to restock notifications of a specific product variant. It also triggers the `restock-notification.restocked` event whenever a product variant's stock quantity is above a specified threshold. The event's payload includes the ID of the product variant and the customer emails subscribed to it. You can pair this with a subscriber that listens to that event and sends a notification to the customer using a [Notification plugin](../notifications/). --- @@ -83,7 +83,7 @@ npm run start ### 2. Subscribe to Variant Restock Notifications -Then, send a `POST` request to the endpoint `/restock-notifications/variants/` to subscribe to restock notifications of a product variant ID. Note that `` refers to the URL fo your Medusa backend, which is `http://localhost:9000` during development, and `` refers to the ID of the product variant you're subscribing to. +Then, send a `POST` request to the API Route `/restock-notifications/variants/` to subscribe to restock notifications of a product variant ID. Note that `` refers to the URL fo your Medusa backend, which is `http://localhost:9000` during development, and `` refers to the ID of the product variant you're subscribing to. :::note @@ -91,7 +91,7 @@ You can only subscribe to product variants that are out-of-stock. Otherwise, you ::: -The endpoint accepts the following request body parameters: +The API Route accepts the following request body parameters: 1. `email`: a string indicating the email that is subscribing to the product variant's restock notification. 2. `sales_channel_id`: an optional string indicating the ID of the sales channel to check the stock quantity in when subscribing. This is useful if you're using multi-warehouse modules, as the product variant's quantity is checked correctly when checking if it's out of stock. Alternatively, you can pass the [publishable API key in the header of the request](../../development/publishable-api-keys/storefront/use-in-requests.md) and the sales channel will be derived from it. @@ -100,7 +100,7 @@ The endpoint accepts the following request body parameters: After subscribing to the out-of-stock variant, change its stock quantity to the minimum inventory required to test out the event trigger. The new stock quantity should be any value above `0` if you didn't set the `inventory_required` option. -You can use the [Medusa admin](../../user-guide/products/manage.mdx#manage-product-variants) or the [Admin REST API endpoints](https://docs.medusajs.com/api/admin#products_postproductsproductvariantsvariant) to update the quantity. +You can use the [Medusa admin](../../user-guide/products/manage.mdx#manage-product-variants) or the [Admin REST API Routes](https://docs.medusajs.com/api/admin#products_postproductsproductvariantsvariant) to update the quantity. After you update the quantity, you can see the `restock-notification.restocked` triggered and logged in the Medusa backend logs. If you've implemented the notification sending, this is where it'll be triggered and a notification will be sent. diff --git a/www/apps/docs/content/plugins/other/wishlist.md b/www/apps/docs/content/plugins/other/wishlist.md index 2f55f771b0..359572d25c 100644 --- a/www/apps/docs/content/plugins/other/wishlist.md +++ b/www/apps/docs/content/plugins/other/wishlist.md @@ -56,11 +56,11 @@ Before testing the plugin, run the following command in the directory of the Med npx medusa develop ``` -The plugin exposes four endpoints. +The plugin exposes four API Routes. -### Add Item to Wishlist Endpoint +### Add Item to Wishlist API Route -The `POST` endpoint at `/store/customer//wishlist` allows customers to add items to their existing or new wishlist, where `` is the ID of the customer. It accepts the following body parameters: +The `POST` API Route at `/store/customer//wishlist` allows customers to add items to their existing or new wishlist, where `` is the ID of the customer. It accepts the following body parameters: - `variant_id`: a string indicating the ID of the product variant to add to the wishlist. - `quantity`: (optional) a number indicating the quantity of the product variant. @@ -68,27 +68,27 @@ The `POST` endpoint at `/store/customer//wishlist` allows customers The request returns the full customer object. The wishlist is available at `customer.metadata.wishlist`, where its value is an array of items. -### Delete Item from Wishlist Endpoint +### Delete Item from Wishlist API Route -The `DELETE` endpoint at `/store/customer//wishlist` allows customers to delete items from their wishlist, where `` is the ID of the customer. +The `DELETE` API Route at `/store/customer//wishlist` allows customers to delete items from their wishlist, where `` is the ID of the customer. -The endpoint accepts one request body parameter `index`, which indicates the index of the item in the `customer.metadata.wishlist` array. +The API Route accepts one request body parameter `index`, which indicates the index of the item in the `customer.metadata.wishlist` array. The request returns the full customer object. The wishlist is available at `customer.metadata.wishlist`, where its value is an array of items. -#### Generate Share Token Endpoint +#### Generate Share Token API Route -The `POST` endpoint at `/store/customer//wishlist/share-token` allows customers to retrieve a token that can be used to access the wishlist, where `` is the ID of the customer. +The `POST` API Route at `/store/customer//wishlist/share-token` allows customers to retrieve a token that can be used to access the wishlist, where `` is the ID of the customer. -The endpoint doesn't accept any request body parameters. +The API Route doesn't accept any request body parameters. The request returns an object in the response having the property `share_token`, being the token that can be used to access the wishlist. -#### Access Wishlist with Token Endpoint +#### Access Wishlist with Token API Route -The `GET` endpoint at `/wishlists/` allows anyone to access the wishlist using its token, where `` is the token retrieved from the [Generate Share Token Endpoint](#generate-share-token-endpoint). +The `GET` API Route at `/wishlists/` allows anyone to access the wishlist using its token, where `` is the token retrieved from the [Generate Share Token API Route](#generate-share-token-api-token). -The endpoint doesn't accept any request body parameters. +The API Route doesn't accept any request body parameters. The request returns an object in the response having the following properties: diff --git a/www/apps/docs/content/plugins/payment/klarna.md b/www/apps/docs/content/plugins/payment/klarna.md index d8ed3cafe9..d5ea449e7b 100644 --- a/www/apps/docs/content/plugins/payment/klarna.md +++ b/www/apps/docs/content/plugins/payment/klarna.md @@ -64,7 +64,7 @@ Where: Finally, in `medusa-config.js`, add the Klarna plugin to the `plugins` array with the necessary configurations: -```jsx title=medusa-config.js +```js title=medusa-config.js const plugins = [ // other plugins... { diff --git a/www/apps/docs/content/plugins/payment/paypal.md b/www/apps/docs/content/plugins/payment/paypal.md index d4ff443ee2..a149db7b0b 100644 --- a/www/apps/docs/content/plugins/payment/paypal.md +++ b/www/apps/docs/content/plugins/payment/paypal.md @@ -25,7 +25,7 @@ In addition, you need to configure a webhook listener on your PayPal Developer D Webhooks are used in scenarios where the customer might leave the page during the authorization and before the checkout flow is fully complete. It will then create the order or swap after the payment is authorized if they weren’t created. -The endpoint for PayPal webhook integration with your Medusa backend should be set to `{BACKEND_URL}/paypal/hooks`. Make sure to replace `{BACKEND_URL}` with the URL to your backend. +The API Route for PayPal webhook integration with your Medusa backend should be set to `{BACKEND_URL}/paypal/hooks`. Make sure to replace `{BACKEND_URL}` with the URL to your backend. Additionally, you need a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../development/backend/install.mdx) to get started. @@ -62,7 +62,7 @@ Notice that during development it’s highly recommended to set `PAYPAL_SANDBOX` Then, in `medusa-config.js`, add the PayPal plugin to the `plugins` array with the configurations necessary: -```jsx title=medusa-config.js +```js title=medusa-config.js const plugins = [ // other plugins... { diff --git a/www/apps/docs/content/plugins/payment/stripe.mdx b/www/apps/docs/content/plugins/payment/stripe.mdx index d19cd4a36d..47beec58cb 100644 --- a/www/apps/docs/content/plugins/payment/stripe.mdx +++ b/www/apps/docs/content/plugins/payment/stripe.mdx @@ -54,7 +54,7 @@ Next, you need to add configurations for your stripe plugin. In `medusa-config.js` add the following at the end of the `plugins` array: -```jsx title=medusa-config.js +```js title=medusa-config.js const plugins = [ // ... { diff --git a/www/apps/docs/content/plugins/search/algolia.md b/www/apps/docs/content/plugins/search/algolia.md index a9aa450810..55de0a9034 100644 --- a/www/apps/docs/content/plugins/search/algolia.md +++ b/www/apps/docs/content/plugins/search/algolia.md @@ -197,9 +197,9 @@ Run your Medusa backend with the following command: npx medusa develop ``` -The quickest way to test that the integration is working is by sending a `POST` request to `/store/products/search`. This endpoint accepts a `q` body parameter of the query to search for and returns in the result the products that match this query. +The quickest way to test that the integration is working is by sending a `POST` request to `/store/products/search`. This API Route accepts a `q` body parameter of the query to search for and returns in the result the products that match this query. -![Postman request send to the search endpoint that retrieves products using Algolia](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000054/Medusa%20Docs/Algolia/IHeTsi7_ymhb2p.png) +![Postman request send to the search API Route that retrieves products using Algolia](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000054/Medusa%20Docs/Algolia/IHeTsi7_ymhb2p.png) You can also check that the products are properly indexed by opening your Algolia dashboard and choosing Search from the left sidebar. You’ll find your products that are on your Medusa backend added there. @@ -256,25 +256,24 @@ Then, add the necessary environment variables: ```bash NEXT_PUBLIC_SEARCH_APP_ID= NEXT_PUBLIC_SEARCH_API_KEY= -NEXT_PUBLIC_SEARCH_INDEX_NAME=products +NEXT_PUBLIC_INDEX_NAME=products ``` Where `` and `` are respectively the Application ID and Search-Only API Key on the [API Keys page](#retrieve-api-keys). Finally, change the code in `src/lib/search-client.ts` to the following: -```jsx title=src/lib/search-client.ts +```ts title=src/lib/search-client.ts import algoliasearch from "algoliasearch/lite" const appId = process.env.NEXT_PUBLIC_SEARCH_APP_ID || "" -const apiKey = - process.env.NEXT_PUBLIC_SEARCH_API_KEY || "test_key" +const apiKey = process.env.NEXT_PUBLIC_SEARCH_API_KEY || "" export const searchClient = algoliasearch(appId, apiKey) export const SEARCH_INDEX_NAME = - process.env.NEXT_PUBLIC_SEARCH_INDEX_NAME || "products" + process.env.NEXT_PUBLIC_INDEX_NAME || "products" ``` If you run your Next.js Starter Template now while the Medusa backend is running, the search functionality will be available in your storefront. diff --git a/www/apps/docs/content/plugins/search/meilisearch.md b/www/apps/docs/content/plugins/search/meilisearch.md index 1b9890de66..c015c884d8 100644 --- a/www/apps/docs/content/plugins/search/meilisearch.md +++ b/www/apps/docs/content/plugins/search/meilisearch.md @@ -52,7 +52,7 @@ Where `` is the host of your MeiliSearch instance. By def Finally, in `medusa-config.js` add the following item into the `plugins` array: -```jsx title=medusa-config.js +```js title=medusa-config.js const plugins = [ // ... { @@ -76,7 +76,7 @@ const plugins = [ Under the `settings` key of the plugin's options, you can add settings specific to each index. The settings are of the following format: -```js +```js title=medusa-config.js const plugins = [ // ... { @@ -164,9 +164,9 @@ Then, run the Medusa backend: npx medusa develop ``` -The quickest way to test that the integration is working is by sending a `POST` request to `/store/products/search`. This endpoint accepts a `q` body parameter of the query to search for and returns in the result the products that match this query. +The quickest way to test that the integration is working is by sending a `POST` request to `/store/products/search`. This API Route accepts a `q` body parameter of the query to search for and returns in the result the products that match this query. -![Postman request to search endpoint that shows results returned from the search engine](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000265/Medusa%20Docs/MeiliSearch/RCGquxU_um3dvn.png) +![Postman request to search API Route that shows results returned from the search engine](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000265/Medusa%20Docs/MeiliSearch/RCGquxU_um3dvn.png) You can also check that the products are properly indexed by opening the MeiliSearch host URL in your browser, which is `http://127.0.0.1:7700/` by default. You’ll find your products that are on your Medusa backend added there. @@ -236,7 +236,7 @@ Then, add the necessary environment variables: ```bash NEXT_PUBLIC_SEARCH_ENDPOINT= NEXT_PUBLIC_SEARCH_API_KEY= -NEXT_PUBLIC_SEARCH_INDEX_NAME=products +NEXT_PUBLIC_INDEX_NAME=products ``` Make sure to replace `` with your MeiliSearch host and `` with the API key you created as instructed in the [Storefront Prerequisites](#storefront-prerequisites) section. diff --git a/www/apps/docs/content/recipes/b2b.mdx b/www/apps/docs/content/recipes/b2b.mdx index 4156cfa111..a878fe04d4 100644 --- a/www/apps/docs/content/recipes/b2b.mdx +++ b/www/apps/docs/content/recipes/b2b.mdx @@ -248,21 +248,21 @@ Each of the entities you create can be controlled using custom logic. --- -## Create an Endpoint to Check Customers +## Create an API Route to Check Customers On the frontend clients communicating with your store, such as the storefront, you’ll need to check whether the currently logged-in customer is a B2B customer. -The endpoint’s logic differs based on how you’ve implemented the B2B logic. For example, if you’ve used the `is_b2b` flag in the customer group, your endpoint can check whether that flag is enabled for the logged-in customer. +The API Route's logic differs based on how you’ve implemented the B2B logic. For example, if you’ve used the `is_b2b` flag in the customer group, your API Route can check whether that flag is enabled for the logged-in customer. -Medusa allows you to create custom endpoints exposed as REST APIs. +Medusa allows you to create custom API Routes exposed as REST APIs. @@ -271,53 +271,53 @@ Medusa allows you to create custom endpoints exposed as REST APIs. Example Implementation -Here’s an example of an endpoint that allows you to check the customer’s group and whether it has the `is_b2b` flag enabled: +For example, create the following API Route that allows you to check the customer’s group and whether it has the `is_b2b` flag enabled: -```ts title=src/api/index.ts -import { CustomerService } from "@medusajs/medusa" -import { Router } from "express" -import { requireCustomerAuthentication } from "@medusajs/medusa" -import cors from "cors" -import { ConfigModule } from "@medusajs/medusa" -import { getConfigFile } from "medusa-core-utils" +```ts title=src/api/store/customers/is-b2b/route.ts +import type { + CustomerService, + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" -export default (rootDirectory) => { - const router = Router() - const { configModule } = getConfigFile( - rootDirectory, - "medusa-config" +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const customerService: CustomerService = req.scope.resolve( + "customerService" ) - const corsOptions = { - origin: configModule.projectConfig.store_cors.split(","), - credentials: true, - } - - router.options("/store/customers/is-b2b", cors(corsOptions)) - router.get( - "/store/customers/is-b2b", - cors(corsOptions), - requireCustomerAuthentication(), - async (req, res) => { - const customerService: CustomerService = req.scope.resolve( - "customerService" - ) - - const customer = await customerService - .retrieve(req.user.customer_id, { - relations: ["groups"], - }) - - const is_b2b = customer.groups.some( - (group) => group.metadata.is_b2b === "true" - ) - - return res.json({ - is_b2b, + const customer = await customerService + .retrieve(req.user.customer_id, { + relations: ["groups"], }) - }) - return router + const is_b2b = customer.groups.some( + (group) => group.metadata.is_b2b === "true" + ) + + return res.json({ + is_b2b, + }) +} +``` + +Then add the `requireCustomerAuthentication` middleware in `src/api/middlewares.ts` that ensures only authenticated customer can access this API Route: + +```ts title=src/api/middlewares.ts +import { + requireCustomerAuthentication, + type MiddlewaresConfig, +} from "@medusajs/medusa" + +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/customers/is-b2b", + middlewares: [requireCustomerAuthentication()], + }, + ], } ``` diff --git a/www/apps/docs/content/recipes/digital-products.mdx b/www/apps/docs/content/recipes/digital-products.mdx index 263e30be75..2b01ccaa05 100644 --- a/www/apps/docs/content/recipes/digital-products.mdx +++ b/www/apps/docs/content/recipes/digital-products.mdx @@ -232,19 +232,19 @@ npx medusa migrations run --- -## Add Custom Endpoints +## Add Custom API Routes -After creating your entity, you need to create custom admin endpoints that allow you to access and manipulate that entity. The endpoints necessary vary based on your case, but generally speaking, you'll need endpoints to perform Create, Read, Update, and Delete (CRUD) functionalities. +After creating your entity, you need to create custom admin API Routes that allow you to access and manipulate that entity. The API Routes necessary vary based on your case, but generally speaking, you'll need API Routes to perform Create, Read, Update, and Delete (CRUD) functionalities. :::tip -The Medusa backend provides the necessary endpoints for the actual file upload. So, you don’t need to create endpoints for that. +The Medusa backend provides the necessary API Routes for the actual file upload. So, you don’t need to create API Routes for that. ::: -You can also create custom storefront endpoints that allow you to show information related to the downloadable digital product if this information isn't stored within the `Product` or `ProductVariant` entities. +You can also create custom storefront API Routes that allow you to show information related to the downloadable digital product if this information isn't stored within the `Product` or `ProductVariant` entities. -Creating an endpoint also requires creating a service, which is a class that typically holds utility methods for an entity. You can implement the CRUD functionalities as methods within the service, then access the service in an endpoint and use its methods. +Creating an API Route also requires creating a service, which is a class that typically holds utility methods for an entity. You can implement the CRUD functionalities as methods within the service, then access the service in an API Route and use its methods. -Example: List and Create Endpoints +Example: List and Create API Routes -This example showcases how you can create the list and create endpoints for digital products. These endpoints are chosen in particular as they’re used in later parts of this recipe. You may follow the same instructions to create other necessary endpoints. +This example showcases how you can create the list and create API Routes for digital products. These API Routes are chosen in particular as they’re used in later parts of this recipe. You may follow the same instructions to create other necessary API Routes. -Before creating the endpoints, you’ll create the `ProductMediaService`. Create the file `src/services/product-media.ts` with the following content: +Before creating the API Routes, you’ll create the `ProductMediaService`. Create the file `src/services/product-media.ts` with the following content: ```ts title=src/services/product-media.ts import { @@ -455,15 +455,43 @@ export default ProductMediaService This service implements the necessary methods to perform the basic CRUD operations. You can add any other method if necessary. -You can now create the endpoints. To create the “create product media” endpoint, create the file `src/api/routes/admin/product-media/create.ts` with the following content: +You can now create the API Routes. Create the file `src/api/admin/product-media/route.ts` with the following content: -```ts title=src/api/routes/admin/product-media/create.ts -import { Request, Response } from "express" +```ts title=src/api/admin/product-media/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import ProductMediaService - from "../../../../services/product-media" + from "../../../services/product-media" +import { MediaType } from "../../../models/product-media" -// create a product media for a variant -export default async (req: Request, res: Response) => { +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const productMediaService = req.scope.resolve< + ProductMediaService + >("productMediaService") + // omitting pagination for simplicity + const [productMedias, count] = await productMediaService + .listAndCount({ + type: MediaType.MAIN, + }, { + relations: ["variant"], + } + ) + + res.json({ + product_medias: productMedias, + count, + }) +} + +export const POST = async ( + req: MedusaRequest, + res: MedusaResponse +) => { // validation omitted for simplicity const { variant_id, @@ -488,136 +516,10 @@ export default async (req: Request, res: Response) => { } ``` -This creates an endpoint the accepts the necessary data to create a product media, then returns the created product media. +This creates two API Routes: -Next, create the “list product media” endpoint by creating the file `src/api/routes/admin/product-media/list.ts` with the following content: - -```ts title=src/api/routes/admin/product-media/list.ts -import { Request, Response } from "express" -import ProductMediaService - from "../../../../services/product-media" -import { MediaType } from "../../../../models/product-media" - -// retrieve a list of product medias -export default async (req: Request, res: Response) => { - const productMediaService = req.scope.resolve< - ProductMediaService - >("productMediaService") - // omitting pagination for simplicity - const [productMedias, count] = await productMediaService - .listAndCount({ - type: MediaType.MAIN, - }, { - relations: ["variant"], - } - ) - - res.json({ - product_medias: productMedias, - count, - }) -} -``` - -This retrieves a list of product media records that have the type `main`. It also retrieves the relations `variant` and `variant.product` to access the product media’s variant and main product. - -To use these endpoints, you need to export them in a router that’s returned by `src/api/index.ts`. First, create the file `src/api/routes/admin/product-media/index.ts` that registers the product media endpoints you created: - -```ts title=src/api/routes/admin/product-media/index.ts -import { wrapHandler } from "@medusajs/utils" -import { Router } from "express" -import create from "./create" -import list from "./list" - -const router = Router() - -export default (adminRouter: Router) => { - adminRouter.use("/product-media", router) - - router.get("/", wrapHandler(list)) - router.post("/", wrapHandler(create)) -} -``` - -Then, create the file `src/api/routes/admin/index.ts` if it doesn’t already exist and add the following in it: - -```ts title=src/api/routes/admin/index.ts -import { Router } from "express" -import productMediaRoutes from "./product-media" - -// Initialize a custom router -const router = Router() - -export function attachAdminRoutes(adminRouter: Router) { - productMediaRoutes(adminRouter) - - // ... exisiting endpoints -} -``` - -In this file you import the function in `src/api/routes/admin/product-media/index.ts` that registers the necessary routes and pass it the admin router, which this file’s function accepts as a parameter. - -If the file `src/api/routes/admin/index.ts` wasn’t already created, make sure to import it in `src/api/index.ts` and use it to register the product media endpoints: - -```ts title=src/api/routes/admin/index.ts -import { Router } from "express" -import cors from "cors" -import bodyParser from "body-parser" -import { ConfigModule } from "@medusajs/medusa" -import { getConfigFile } from "medusa-core-utils" -import { attachStoreRoutes } from "./routes/store" -import { attachAdminRoutes } from "./routes/admin" - -export default (rootDirectory: string): Router | Router[] => { - // Read currently-loaded medusa config - const { configModule } = getConfigFile( - rootDirectory, - "medusa-config" - ) - const { projectConfig } = configModule - - // Set up our CORS options objects, based on config - const storeCorsOptions = { - origin: projectConfig.store_cors.split(","), - credentials: true, - } - - const adminCorsOptions = { - origin: projectConfig.admin_cors.split(","), - credentials: true, - } - - // Set up express router - const router = Router() - - // Set up root routes for store and admin endpoints, - // with appropriate CORS settings - router.use( - "/store", - cors(storeCorsOptions), - bodyParser.json() - ) - router.use( - "/admin", - cors(adminCorsOptions), - bodyParser.json() - ) - - // Set up routers for store and admin endpoints - const storeRouter = Router() - const adminRouter = Router() - - // Attach these routers to the root routes - router.use("/store", storeRouter) - router.use("/admin", adminRouter) - - // Attach custom routes to these routers - attachStoreRoutes(storeRouter) - attachAdminRoutes(adminRouter) - - return router -} -``` +- a `GET` API Route at `/admin/product-media` that retrieves a list of product media records that have the type `main`. It also retrieves the relations `variant` and `variant.product` to access the product media’s variant and main product. +- a `POST` API Route at `/admin/product-media` that accepts the necessary data to create a product media, then returns the created product media. @@ -628,7 +530,7 @@ export default (rootDirectory: string): Router | Router[] => { The Medusa admin dashboard provides merchants with an easy-to-use interface to manage their store's data and settings. It's also extendable, so you can add widgets, pages, and setting pages relevant to your use case. -To add an interface that allows the admin user to upload digital products, you can create custom widgets or pages that use the routes you created. You can use the [Protected Files Upload endpoint](https://docs.medusajs.com/api/admin#uploads_postuploadsprotected). +To add an interface that allows the admin user to upload digital products, you can create custom widgets or pages that use the routes you created. You can use the [Protected Files Upload API Route](https://docs.medusajs.com/api/admin#uploads_postuploadsprotected). Example -Before you customize the Next.js storefront, you need to add a store endpoint in your backend. +Before you customize the Next.js storefront, you need to add a store API Route in your backend. -Create the file `src/api/routes/store/product-media/list.ts` with the following content: +Create the file `src/api/store/product-media/route.ts` with the following content: -```ts title=src/api/routes/store/product-media/list.ts -import { Request, Response } from "express" +```ts title=src/api/store/product-media/route.ts +import type { + MedusaRequest, + MedusaResponse, +} from "@medusajs/medusa" import ProductMediaService - from "../../../../services/product-media" -import { MediaType } - from "../../../../models/product-media" + from "../../../services/product-media" +import { MediaType } from "../../../models/product-media" - -// retrieve a list of product medias -export default async (req: Request, res: Response) => { +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { const productMediaService = req.scope.resolve< ProductMediaService >("productMediaService") @@ -1206,103 +1111,7 @@ export default async (req: Request, res: Response) => { } ``` -This adds a store endpoint that returns a list of product medias of type `preview`. It also allows you to pass query parameters to filter the returned products medias. - -To use this endpoint, you need to export it in a router that’s returned by `src/api/index.ts`. First, create the file `src/api/routes/store/product-media/index.ts` that registers the product media endpoint you created: - -```ts title=src/api/routes/store/product-media/index.ts -import { wrapHandler } from "@medusajs/utils" -import { Router } from "express" -import list from "./list" - -const router = Router() - -export default (storeRouter: Router) => { - storeRouter.use("/product-media", router) - - router.get("/", wrapHandler(list)) -} -``` - -Then, create the file `src/api/routes/store/index.ts` if it doesn’t already exist and add the following in it: - -```ts title=src/api/routes/store/index.ts -import { Router } from "express" -import productMediaRoutes from "./product-media" - -// Initialize a custom router -const router = Router() - -export function attachStoreRoutes(storeRouter: Router) { - productMediaRoutes(storeRouter) - - // existing endpoints... -} -``` - -In this file you import the function in `src/api/routes/store/product-media/index.ts` that registers the necessary routes and pass it the store router, which this file’s function accepts as a parameter. - -If the file `src/api/routes/store/index.ts` wasn’t already created, make sure to import it in `src/api/index.ts` and use it to register the product media endpoints: - -```ts -import { Router } from "express" -import cors from "cors" -import bodyParser from "body-parser" -import { ConfigModule } from "@medusajs/medusa" -import { getConfigFile } from "medusa-core-utils" -import { attachStoreRoutes } from "./routes/store" -import { attachAdminRoutes } from "./routes/admin" - -export default (rootDirectory: string): Router | Router[] => { - // Read currently-loaded medusa config - const { configModule } = getConfigFile( - rootDirectory, - "medusa-config" - ) - const { projectConfig } = configModule - - // Set up our CORS options objects, based on config - const storeCorsOptions = { - origin: projectConfig.store_cors.split(","), - credentials: true, - } - - const adminCorsOptions = { - origin: projectConfig.admin_cors.split(","), - credentials: true, - } - - // Set up express router - const router = Router() - - // Set up root routes for store and admin endpoints, - // with appropriate CORS settings - router.use( - "/store", - cors(storeCorsOptions), - bodyParser.json() - ) - router.use( - "/admin", - cors(adminCorsOptions), - bodyParser.json() - ) - - // Set up routers for store and admin endpoints - const storeRouter = Router() - const adminRouter = Router() - - // Attach these routers to the root routes - router.use("/store", storeRouter) - router.use("/admin", adminRouter) - - // Attach custom routes to these routers - attachStoreRoutes(storeRouter) - attachAdminRoutes(adminRouter) - - return router -} -``` +This adds a store API Route that returns a list of product medias of type `preview`. It also allows you to pass query parameters to filter the returned products medias. Now, you can customize the Next.js storefront to show the preview button. @@ -2228,27 +2037,26 @@ After the customer purchases the digital product you can show a download button Example -Before you implement the storefront changes, you need to create a new endpoint in the backend that ensures that the currently logged-in customer has purchased the digital product and, if so, returns a presigned URL to download it. +Before you implement the storefront changes, you need to create a new API Route in the backend that ensures that the currently logged-in customer has purchased the digital product and, if so, returns a presigned URL to download it. -Create the file `src/api/routes/store/product-media/download.ts` with the following content: +Create the file `src/api/store/product-media/download/[variant_id]/route.ts` with the following content: -```ts title=src/api/routes/store/product-media/download.ts -import { Request, Response } from "express" -import ProductMediaService - from "../../../../services/product-media" -import { - MediaType, -} from "../../../../models/product-media" -import { - AbstractFileService, - CustomerService, - OrderService, +```ts title=src/api/store/product-media/download/route.ts +import type { + AbstractFileService, + MedusaRequest, + MedusaResponse, + OrderService, ProductVariant, } from "@medusajs/medusa" +import ProductMediaService + from "../../../../services/product-media" +import { MediaType } from "../../../../models/product-media" - -// download a purchased product -export default async (req: Request, res: Response) => { +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { const variantId = req.params.variant_id if (!variantId) { throw new Error("Variant ID is required") @@ -2302,31 +2110,27 @@ export default async (req: Request, res: Response) => { } ``` -Then, register the new endpoint in `src/api/routes/store/product-media/index.ts`: +Then, add the `requireCustomerAuthentication` middleware to this API Route in `src/api/middlewares.ts`: -```ts title=src/api/routes/store/product-media/index.ts -import { wrapHandler } from "@medusajs/utils" +```ts title=src/api/middlewares.ts import { - requireCustomerAuthentication, + requireCustomerAuthentication, + type MiddlewaresConfig, } from "@medusajs/medusa" -import download from "./download" -// ... - -export default (storeRouter: Router) => { - // ... - - router.get( - "/download/:variant_id", - requireCustomerAuthentication(), - wrapHandler(download) - ) +export const config: MiddlewaresConfig = { + routes: [ + { + matcher: "/store/product-media/download/*", + middlewares: [requireCustomerAuthentication()], + }, + ], } ``` -Note that you use the `requireCustomerAuthentication` middleware to ensure only logged-in customers can access this endpoint. +This ensures that only logged-in customers can access this API Route. -You can use this endpoint in your storefront to add a button that allows downloading the purchased digital product. +You can use this API Route in your storefront to add a button that allows downloading the purchased digital product. To mask the presigned URL, create a Next.js API route at `src/app/api/download/main/[variant_id]/route.ts` with the following content: diff --git a/www/apps/docs/content/recipes/marketplace.mdx b/www/apps/docs/content/recipes/marketplace.mdx index 90e018fef2..cc1080e15e 100644 --- a/www/apps/docs/content/recipes/marketplace.mdx +++ b/www/apps/docs/content/recipes/marketplace.mdx @@ -149,7 +149,7 @@ Throughout your development, you'll likely need access to the logged-in user. Fo -```ts +```ts title=src/services/user.ts import { Lifetime } from "awilix" import { UserService as MedusaUserService, @@ -272,7 +272,7 @@ To listen to events, you need to create Subscribers that subscribe a handler met To listen to the `order.placed` event, create the file `src/subscribers/orderNotifier.ts` with the following content: -```ts +```ts title=src/subscribers/orderNotifier.ts class OrderNotifierSubscriber { constructor({ eventBusService }) { eventBusService.subscribe("order.placed", this.handleOrder) @@ -396,7 +396,7 @@ Medusa's [admin plugin](../admin/quickstart.mdx) can be extended to add widgets ## Implement Role-Based Access Control -In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or endpoints. +In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or API Routes. If you want to implement this functionality, you can follow the RBAC recipe. diff --git a/www/apps/docs/content/recipes/omnichannel.mdx b/www/apps/docs/content/recipes/omnichannel.mdx index a95931efce..19cdd95922 100644 --- a/www/apps/docs/content/recipes/omnichannel.mdx +++ b/www/apps/docs/content/recipes/omnichannel.mdx @@ -89,7 +89,7 @@ You can implement the customer journey and design for your storefronts that lead Medusa’s architecture also makes it easier to integrate any third-party services necessary to provide a better customer experience with a plugin. This plugin’s functionality can be accessible to the storefronts connected to the Medusa backend. -For example, if you’ve integrated a search plugin like Algolia in the Medusa backend, the storefronts can utilize it through the Search Products endpoint. Another example is installing the Stripe payment plugin on the backend and using it in your storefronts to make payments before placing an order. +For example, if you’ve integrated a search plugin like Algolia in the Medusa backend, the storefronts can utilize it through the Search Products API Route. Another example is installing the Stripe payment plugin on the backend and using it in your storefronts to make payments before placing an order. @@ -127,7 +127,7 @@ In the case that you’ve created a custom entity or extended a core entity, you If you stored the personalized data in the `metadata` of the Line Items, those same Line Items are associated with the placed order. So, by expanding the `items` relation on the `Order` entity, you can retrieve the `metadata` attribute of the Line Items. -In the case that you’ve created a custom entity or extended a core entity, you can create a custom endpoint that handles retrieving the personalization data. If the entity you’ve created or customized is associated with the Order entity, you can alternatively expand it similarly to the `items` relation. +In the case that you’ve created a custom entity or extended a core entity, you can create a custom API Route that handles retrieving the personalization data. If the entity you’ve created or customized is associated with the Order entity, you can alternatively expand it similarly to the `items` relation. If you want to show the personalized data in the Medusa admin, you can extend the Medusa admin to add a widget, a UI route, or a setting page and show the personalized data. @@ -173,9 +173,6 @@ You can also listen to other [Order-related events](../development/events/events Alternatively, you can create a fulfillment service that integrates a third-party service or mechanism to fulfill the personalized product. This is useful if you want the fulfillment of personalized products to be embedded into Medusa’s existing order fulfillment. -- Create a Subscriber -- Create a Fulfillment Service -
-Example: Search Products By Barcode Endpoint +Example: Search Products By Barcode API Route -Here’s an example of creating a custom endpoint that searches product variants by a barcode: +Here’s an example of creating a custom API Route at `/store/pos/search-barcode` that searches product variants by a barcode: -```ts title=src/api/index.ts -import { Request, Response, Router } from "express" -import cors from "cors" -import { - ConfigModule, - errorHandler, - ProductVariantService, - wrapHandler, +```ts title=src/api/store/pos/search-barcode/route.ts +import type { + MedusaRequest, + MedusaResponse, + ProductVariantService, } from "@medusajs/medusa" -import { getConfigFile } from "medusa-core-utils" import { MedusaError } from "@medusajs/utils" -export default (rootDirectory: string): Router | Router[] => { - // Read currently-loaded medusa config - const { configModule } = getConfigFile( - rootDirectory, - "medusa-config" - ) - const { projectConfig } = configModule - - // Set up our CORS options objects, based on config - const storeCorsOptions = { - origin: projectConfig.store_cors.split(","), - credentials: true, - } - - // Set up express router - const router = Router() - - router.get( - "/pos/search-barcode", - cors(storeCorsOptions), - wrapHandler( - async (req: Request, res: Response) => { - const barcode = (req.query.barcode as string) || "" - if (!barcode) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - "Barcode is required" - ) - } - // get product service - const productVariantService = req.scope.resolve< - ProductVariantService - >("productVariantService") - - // retrieve product variants by barcode - const productVariants = await productVariantService - .list({ - barcode, - }) - - res.json({ - product_variants: productVariants, - }) - } +export const GET = async ( + req: MedusaRequest, + res: MedusaResponse +) => { + const barcode = (req.query.barcode as string) || "" + if (!barcode) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + "Barcode is required" ) - ) + } + // get product service + const productVariantService = req.scope.resolve< + ProductVariantService + >("productVariantService") - router.use(errorHandler()) + // retrieve product variants by barcode + const productVariants = await productVariantService + .list({ + barcode, + }) - return router + res.json({ + product_variants: productVariants, + }) } ``` diff --git a/www/apps/docs/content/starters/nextjs-medusa-starter.mdx b/www/apps/docs/content/starters/nextjs-medusa-starter.mdx index 7cc317bc3a..3bdfd5fe1a 100644 --- a/www/apps/docs/content/starters/nextjs-medusa-starter.mdx +++ b/www/apps/docs/content/starters/nextjs-medusa-starter.mdx @@ -198,7 +198,7 @@ The Next.js Starter Storefront by default is compatible with MeiliSearch. To enable or disable the search engine, change the value of the feature in `store.config.json`: -```json +```json title=store.config.json { "features": { "search": false @@ -217,12 +217,12 @@ In your Next.js Starter Storefront, set the environment variables necessary for ```json NEXT_PUBLIC_SEARCH_ENDPOINT= NEXT_PUBLIC_SEARCH_API_KEY= -NEXT_PUBLIC_SEARCH_INDEX_NAME=products +NEXT_PUBLIC_INDEX_NAME=products ``` `` is the URL MeiliSearch is running on. The default is `http://127.0.0.1:7700`. -`NEXT_PUBLIC_SEARCH_INDEX_NAME` is the index name of the products in MeiliSearch. By default, it’s `products`. +`NEXT_PUBLIC_INDEX_NAME` is the index name of the products in MeiliSearch. By default, it’s `products`. `` is the API key used to search through MeiliSearch indexes. To create a new API Key, make sure that the MeiliSearch service is running and send the following request: @@ -260,21 +260,21 @@ In your Next.js Starter Storefront, set the environment variables necessary for ```bash NEXT_PUBLIC_SEARCH_APP_ID= NEXT_PUBLIC_SEARCH_API_KEY= -NEXT_PUBLIC_SEARCH_INDEX_NAME=products +NEXT_PUBLIC_INDEX_NAME=products ``` Where `` and `` are the Algolia App ID and Algolia Search API Key respectively. You can retrieve them from Algolia by going to [API Keys](https://www.algolia.com/account/api-keys/all) in your account settings. -`NEXT_PUBLIC_SEARCH_INDEX_NAME` is the index name of the products in Algolia. By default, it’s `products`. +`NEXT_PUBLIC_INDEX_NAME` is the index name of the products in Algolia. By default, it’s `products`. Next, change the content of `src/lib/search-client.ts` to the following: -```bash +```ts title=src/lib/search-client.ts import algoliasearch from "algoliasearch/lite" -const appId = process.env.NEXT_PUBLIC_SEARCH_APP_ID || "" // You should add this to your environment variables +const appId = process.env.NEXT_PUBLIC_SEARCH_APP_ID || "" -const apiKey = process.env.NEXT_PUBLIC_SEARCH_API_KEY || "test_key" +const apiKey = process.env.NEXT_PUBLIC_SEARCH_API_KEY || "" export const searchClient = algoliasearch(appId, apiKey) @@ -334,8 +334,8 @@ To change the port, change the `develop` command in `package.json` to the follow ```json "scripts": { - //other scripts - "dev": "next dev -p " + //other scripts + "dev": "next dev -p " } ``` diff --git a/www/apps/docs/content/storefront/roadmap.mdx b/www/apps/docs/content/storefront/roadmap.mdx index d16d0af568..33c3304f20 100644 --- a/www/apps/docs/content/storefront/roadmap.mdx +++ b/www/apps/docs/content/storefront/roadmap.mdx @@ -59,7 +59,7 @@ Publishable API Keys are used to scope API requests to defined resources, such a Also, when you're using Medusa's JS or React clients, you can pass the publishable API key when you first initialize the clients and it will be appended to all requests you send. -For example, you can create a publishable API key and associate it with one or more sales channels. Then, when you pass the publishable API key in the header of the request to the List Products endpoint, only products associated with that sales channel will be retrieved. The alternative would be to pass the sales channels as query parameters to the request. +For example, you can create a publishable API key and associate it with one or more sales channels. Then, when you pass the publishable API key in the header of the request to the List Products API Route, only products associated with that sales channel will be retrieved. The alternative would be to pass the sales channels as query parameters to the request. There are two ways to create a publishable API Key: either using the admin dashboard, which requires the admin plugin to be installed on your Medusa backend, or using the Admin REST APIs. @@ -84,7 +84,7 @@ There are two ways to create a publishable API Key: either using the admin dashb }, ]} /> -After creating the publishable API key and associating it with sales channels, you can pass it in the header of your requests to Store API endpoints. +After creating the publishable API key and associating it with sales channels, you can pass it in the header of your requests to Store API Routes. diff --git a/www/apps/docs/content/troubleshooting/awilix-resolution-error/_custom-registration.md b/www/apps/docs/content/troubleshooting/awilix-resolution-error/_custom-registration.md index 91f93fa190..d3192a2448 100644 --- a/www/apps/docs/content/troubleshooting/awilix-resolution-error/_custom-registration.md +++ b/www/apps/docs/content/troubleshooting/awilix-resolution-error/_custom-registration.md @@ -24,4 +24,4 @@ class CustomService extends TransactionBaseService { export default CustomService ``` -You can learn more about this in the [Middlewares documentation](../../development/endpoints/add-middleware.mdx). +You can learn more about this in the [Middlewares documentation](../../development/api-routes/add-middleware.mdx). diff --git a/www/apps/docs/sidebars.js b/www/apps/docs/sidebars.js index e2c438d0f2..a1659c2b5b 100644 --- a/www/apps/docs/sidebars.js +++ b/www/apps/docs/sidebars.js @@ -1403,11 +1403,11 @@ module.exports = { }, { type: "category", - label: "Endpoint", + label: "API Routes", items: [ { type: "doc", - id: "development/endpoints/overview", + id: "development/api-routes/overview", label: "Overview", }, { @@ -1418,23 +1418,45 @@ module.exports = { }, }, { - type: "doc", - id: "development/endpoints/create", - label: "Create an Endpoint", + type: "category", + label: "Create an API Route", + link: { + type: "doc", + id: "development/api-routes/create", + }, + collapsed: true, + items: [ + { + type: "doc", + id: "development/api-routes/create-express-route", + label: "Express-Router Approach", + }, + ], + }, + { + type: "category", + label: "Create a Middleware", + link: { + type: "doc", + id: "development/api-routes/add-middleware", + }, + collapsed: true, + items: [ + { + type: "doc", + id: "development/api-routes/add-middleware-express-route", + label: "Express-Router Approach", + }, + ], }, { type: "doc", - id: "development/endpoints/add-middleware", - label: "Middleware", - }, - { - type: "doc", - id: "development/endpoints/extend-validator", + id: "development/api-routes/extend-validator", label: "Extend Validator", }, { type: "doc", - id: "development/endpoints/example-logged-in-user", + id: "development/api-routes/example-logged-in-user", label: "Example: Logged-In User", }, ], diff --git a/www/apps/docs/src/providers/Search/index.tsx b/www/apps/docs/src/providers/Search/index.tsx index 5a7b443da8..a3aa362e3f 100644 --- a/www/apps/docs/src/providers/Search/index.tsx +++ b/www/apps/docs/src/providers/Search/index.tsx @@ -59,7 +59,7 @@ const SearchProvider = ({ children }: SearchProviderProps) => { title: "Developing with Medusa", items: [ "Recipes", - "How to create endpoints", + "How to create API routes", "How to create an entity", "How to create a plugin", "How to create an admin widget", diff --git a/www/apps/docs/src/utils/glossary.ts b/www/apps/docs/src/utils/glossary.ts index 5d7458a07c..5fee02e49d 100644 --- a/www/apps/docs/src/utils/glossary.ts +++ b/www/apps/docs/src/utils/glossary.ts @@ -36,15 +36,15 @@ const glossary: GlossaryType[] = [ { title: "Middleware", content: - "A function that can be executed before or after endpoint requests are handled.", + "A function that can be executed before or after API Route requests are handled.", matchTextRegex: /middleware/i, - referenceLink: "/development/endpoints/add-middleware", + referenceLink: "/development/api-routes/add-middleware", }, { - title: "Endpoint", + title: "API Route", content: "REST API routes exposed to frontends or external systems.", - matchTextRegex: /endpoint/i, - referenceLink: "/development/endpoints/overview", + matchTextRegex: /api-routes/i, + referenceLink: "/development/api-routes/overview", }, { title: "Subscriber", diff --git a/www/apps/docs/src/utils/learning-paths.tsx b/www/apps/docs/src/utils/learning-paths.tsx index f57daee124..975b32a6d3 100644 --- a/www/apps/docs/src/utils/learning-paths.tsx +++ b/www/apps/docs/src/utils/learning-paths.tsx @@ -59,7 +59,7 @@ const paths: LearningPathType[] = [ title: "Access logged-in user", description: "Create a middleware that registers the logged-in user in the dependency container.", - path: "/development/endpoints/example-logged-in-user", + path: "/development/api-routes/example-logged-in-user", }, { title: "Extend services", @@ -114,7 +114,7 @@ const paths: LearningPathType[] = [ title: "Implement Role-Based Access Control", path: "/modules/users/backend/rbac", description: - "In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or endpoints.", + "In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or API Routes.", }, { title: "Create a storefront", @@ -370,7 +370,7 @@ const paths: LearningPathType[] = [ Your use case may be more elaborate than what is shown in this recipe.
- Medusa can be customized to add custom entities, endpoints, + Medusa can be customized to add custom entities, API Routes, services, and more.
You can find additional development resources in the{" "} @@ -379,7 +379,7 @@ const paths: LearningPathType[] = [ ), }, { - title: "Create an Endpoint to Check Customers", + title: "Create an API Route to Check Customers", path: "/development/entities/create", descriptionJSX: ( <> @@ -387,7 +387,7 @@ const paths: LearningPathType[] = [ storefront, you’ll need to check if the currently logged-in customer is a normal customer or a B2B customer.
- To do that, you need to create a custom endpoint that handles the + To do that, you need to create a custom API Route that handles the checking based on the custom logic you've chosen to indicate a customer is a B2B customer. @@ -476,9 +476,9 @@ const paths: LearningPathType[] = [ }, { title: "Create Guard Middleware", - path: "/development/endpoints/add-middleware", + path: "/development/api-routes/add-middleware", description: - "To ensure that users who have the privilege can access an endpoint, you must create a middleware that guards admin routes. This middleware will run on all authenticated admin requests to ensure that only allowed users can access an endpoint.", + "To ensure that users who have the privilege can access an API Route, you must create a middleware that guards admin routes. This middleware will run on all authenticated admin requests to ensure that only allowed users can access an API Route.", }, { title: "Create Services", @@ -501,15 +501,15 @@ const paths: LearningPathType[] = [ ), }, { - title: "Create Endpoints", - path: "/development/endpoints/create", + title: "Create API Routes", + path: "/development/api-routes/create", descriptionJSX: ( <> To manage the roles and permissions, you’ll need to create custom - endpoints, typically for Create, Read, Update, and Delete (CRUD) + API Routes, typically for Create, Read, Update, and Delete (CRUD) operations.
- After creating the endpoints, you may test adding roles and + After creating the API Routes, you may test adding roles and permissions, and how they provide different access for different roles and users. @@ -527,9 +527,9 @@ const paths: LearningPathType[] = [ }, { name: "entity-and-api", - label: "Create Entity and Expose it with Endpoints", + label: "Create Entity and Expose it with API Routes", description: - "Learn how to create a new table in your database, then create endpoints to expose and manipulate its data.", + "Learn how to create a new table in your database, then create API Routes to expose and manipulate its data.", steps: [ { title: "Create entity", @@ -540,17 +540,17 @@ const paths: LearningPathType[] = [ title: "Create service", path: "/development/services/create-service", description: - "A service is a class that defines helper methods for your entity. The service will be used by the endpoints to access or modify the entity's data.", + "A service is a class that defines helper methods for your entity. The service will be used by the API Routes to access or modify the entity's data.", }, { - title: "Create endpoints", - path: "/development/endpoints/create", + title: "Create API Routes", + path: "/development/api-routes/create", }, ], finish: { type: "rating", step: { - title: "Congratulations on creating your entity and endpoints!", + title: "Congratulations on creating your entity and API Routes!", description: "Please rate your experience using this recipe.", eventName: "rating_path_entity-and-api", }, @@ -585,8 +585,8 @@ const paths: LearningPathType[] = [ Store REST APIs - : You can send requests directly to the API endpoints without - using Medusa's clients. + : You can send requests directly to the API Routes without using + Medusa's clients. @@ -619,7 +619,7 @@ const paths: LearningPathType[] = [ title: "Use Publishable API Key", path: "/development/publishable-api-keys/storefront/use-in-requests", description: - "After creating the publishable API key and associating it with sales channels, you can pass it in the header of your requests to Store API endpoints.", + "After creating the publishable API key and associating it with sales channels, you can pass it in the header of your requests to Store API Routes.", }, { title: "Add Region Selection", @@ -714,8 +714,8 @@ const paths: LearningPathType[] = [
  • - - Create an Endpoint + + Create an API Route
  • diff --git a/www/apps/docs/vercel.json b/www/apps/docs/vercel.json index e043a63d65..1be82ee6e2 100644 --- a/www/apps/docs/vercel.json +++ b/www/apps/docs/vercel.json @@ -484,6 +484,10 @@ { "source": "/user-guide/price-lists/import", "destination": "/user-guide/price-lists" + }, + { + "source": "/development/endpoints/:path", + "destination": "/development/api-routes/:path" } ], "framework": "docusaurus-2", diff --git a/www/apps/ui/src/content/docs/components/command.mdx b/www/apps/ui/src/content/docs/components/command.mdx index f926234738..134a3f5f73 100644 --- a/www/apps/ui/src/content/docs/components/command.mdx +++ b/www/apps/ui/src/content/docs/components/command.mdx @@ -1,6 +1,6 @@ --- title: "Command" -description: "Renders an unhighlighted code block, useful for one-liners or endpoints" +description: "Renders an unhighlighted code block, useful for one-liners or API Routes" component: true ---