* initialized next.js project * finished markdown sections * added operation schema component * change page metadata * eslint fixes * fixes related to deployment * added response schema * resolve max stack issue * support for different property types * added support for property types * added loading for components * added more loading * type fixes * added oneOf type * removed console * fix replace with push * refactored everything * use static content for description * fixes and improvements * added code examples section * fix path name * optimizations * fixed tag navigation * add support for admin and store references * general enhancements * optimizations and fixes * fixes and enhancements * added search bar * loading enhancements * added loading * added code blocks * added margin top * add empty response text * fixed oneOf parameters * added path and query parameters * general fixes * added base path env variable * small fix for arrays * enhancements * design enhancements * general enhancements * fix isRequired * added enum values * enhancements * general fixes * general fixes * changed oas generation script * additions to the introduction section * added copy button for code + other enhancements * fix response code block * fix metadata * formatted store introduction * move sidebar logic to Tags component * added test env variables * fix code block bug * added loading animation * added expand param + loading * enhance operation loading * made responsive + improvements * added loading provider * fixed loading * adjustments for small devices * added sidebar label for endpoints * added feedback component * fixed analytics * general fixes * listen to scroll for other headings * added sample env file * update api ref files + support new fields * fix for external docs link * added new sections * fix last item in sidebar not showing * move docs content to www/docs * change redirect url * revert change * resolve build errors * configure rewrites * changed to environment variable url * revert changing environment variable name * add environment variable for API path * fix links * fix tailwind settings * remove vercel file * reconfigured api route * move api page under api * fix page metadata * fix external link in navigation bar * update api spec * updated api specs * fixed google lint error * add max-height on request samples * add padding before loading * fix for one of name * fix undefined types * general fixes * remove response schema example * redesigned navigation bar * redesigned sidebar * fixed up paddings * added feedback component + report issue * fixed up typography, padding, and general styling * redesigned code blocks * optimization * added error timeout * fixes * added indexing with algolia + fixes * fix errors with algolia script * redesign operation sections * fix heading scroll * design fixes * fix padding * fix padding + scroll issues * fix scroll issues * improve scroll performance * fixes for safari * optimization and fixes * fixes to docs + details animation * padding fixes for code block * added tab animation * fixed incorrect link * added selection styling * fix lint errors * redesigned details component * added detailed feedback form * api reference fixes * fix tabs * upgrade + fixes * updated documentation links * optimizations to sidebar items * fix spacing in sidebar item * optimizations and fixes * fix endpoint path styling * remove margin * final fixes * change margin on small devices * generated OAS * fixes for mobile * added feedback modal * optimize dark mode button * fixed color mode useeffect * minimize dom size * use new style system * radius and spacing design system * design fixes * fix eslint errors * added meta files * change cron schedule * fix docusaurus configurations * added operating system to feedback data * change content directory name * fixes to contribution guidelines * revert renaming content * added api-reference to documentation workflow * fixes for search * added dark mode + fixes * oas fixes * handle bugs * added code examples for clients * changed tooltip text * change authentication to card * change page title based on selected section * redesigned mobile navbar * fix icon colors * fix key colors * fix medusa-js installation command * change external regex in algolia * change changeset * fix padding on mobile * fix hydration error * update depedencies
5.0 KiB
description, addHowToData
| description | addHowToData |
|---|---|
| Learn how to extend a core repository in Medusa to add custom methods. | true |
How to Extend a Repository
In this document, you’ll learn how to extend a core repository in Medusa.
Overview
Medusa uses Typeorm’s Repositories to perform operations on an entity, such as retrieve or update the entity. Typeorm already provides these basic functionalities within a repository, but sometimes you need to implement a custom implementation to handle the logic behind these operations differently. You might also want to add custom methods related to processing entities that aren’t available in the default repositories.
In this guide, you’ll learn how to extend a repository in the core Medusa package. This guide will use the Product repository as an example to demonstrate the steps.
Word of Caution about Overriding
Extending repositories to add new methods shouldn't cause any issues within your commerce application. However, if you extend them to override their existing methods, you should be aware that this could have negative implications, such as unanticipated bugs, especially when you try to upgrade the core Medusa package to a newer version.
Step 1: Create Repository File
In your Medusa backend, create the file src/repositories/product.ts. This file will hold your extended repository.
Note that the name of the file must be the same as the name of the original repository in the core package. Since in this guide you’re extending the Product repository, it’s named product to match the core. If you’re extending the customer repository, for example, the file should be named customer.ts.
Step 2: Implement Extended Repository
In the file you created, you must retrieve both the repository you're extending along with its entity from the core. You’ll then use the data source exported from the core package to extend the repository.
:::tip
A data source is Typeorm’s connection settings that allows you to connect to your database. You can learn more about it in Typeorm’s documentation.
:::
Here’s an example of the implementation of the extended Product repository:
import { Product } from "@medusajs/medusa"
import {
dataSource,
} from "@medusajs/medusa/dist/loaders/database"
import {
// alias the core repository to not cause a naming conflict
ProductRepository as MedusaProductRepository,
} from "@medusajs/medusa/dist/repositories/product"
export const ProductRepository = dataSource
.getRepository(Product)
.extend({
// it is important to spread the existing repository here.
// Otherwise you will end up losing core properties
...MedusaProductRepository,
/**
* Here you can create your custom function
* For example
*/
customFunction(): void {
// TODO add custom implementation
return
},
})
export default ProductRepository
You first import all necessary resources from the core package: the Product entity, the dataSource instance, and the core’s ProductRepository aliased as MedusaProductRepository to avoid naming conflict.
You then use the dataSource instance to retrieve the Product entity’s repository and extend it using the repository’s extend method. This method is available as part of Typeorm Repository API. This method returns your extended repository.
The extend method accepts an object with all the methods to add to the extended repository.
You must first add the properties of the repository you’re extending, which in this case is the product repository (aliased as MedusaProductRepository). This will ensure you don’t lose core methods, which can lead to the core not working as expected. You add use the spread operator (…) with the MedusaProductRepository to spread its properties.
After that, you can add your custom methods to the repository. In the example above, you add the method customFunction. You can use any name for your methods.
Step 3: Use Your Extended Repository
You can now use your extended repository in other resources such as services or endpoints.
Here’s an example of using it in an endpoint:
import ProductRepository from "./path/to/product.ts"
import EntityManager from "@medusajs/medusa"
export default () => {
// ...
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()
// ...
})
}
Step 4: Test Your Implementation
For changes to take effect, you must transpile your code by running the build command in the root of the Medusa backend:
npm run build
Then, run the following command to start your backend:
npx medusa develop
You should see your custom implementation working as expected.