* 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
7.7 KiB
description, addHowToData
| description | addHowToData |
|---|---|
| Learn how to extend a core entity in Medusa to add custom attributes. | true |
How to Extend an Entity
In this document, you’ll learn how to extend a core entity in Medusa.
Overview
Medusa uses entities to represent tables in the database. As you build your custom commerce application, you’ll often need to add your own properties to those entities. This guide explains the necessary steps to extend core Medusa entities.
This guide will use the Product entity as an example to demonstrate the steps.
Word of Caution about Overriding
Extending entities to add new attributes or methods shouldn't cause any issues within your commerce application. However, if you extend them to override their existing methods or attributes, 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 Entity File
In your Medusa backend, create the file src/models/product.ts. This file will hold your extended entity.
Note that the name of the file must be the same as the name of the original entity in the core package. Since in this guide you’re overriding the Product entity, it’s named product to match the core. If you’re extending the customer entity, for example, the file should be named customer.ts.
Step 2: Implement Extended Entity
In the file you created, you can import the entity you’re extending from the core package, then create a class that extends that entity. You can add in that class the new attributes and methods.
Here’s an example of extending the Product entity:
import { Column, Entity } from "typeorm"
import {
// alias the core entity to not cause a naming conflict
Product as MedusaProduct,
} from "@medusajs/medusa"
@Entity()
export class Product extends MedusaProduct {
@Column()
customAttribute: string
}
(Optional) Step 3: Create a TypeScript Declaration File
If you’re using JavaScript instead of TypeScript in your implementation, you can skip this step.
To ensure that TypeScript is aware of your extended entity and affects the typing of the Medusa package itself, create the file src/index.d.ts with the following content:
export declare module "@medusajs/medusa/dist/models/product" {
declare interface Product {
customAttribute: string;
}
}
Notice that you must pass the attributes you added to the entity into the interface. The attributes will be merged with the attributes defined in the core Product entity.
Step 4: Create Migration
To reflect your entity changes on the database schema, you must create a migration with those changes.
You can learn how to create or generate a migration in this documentation.
Here’s an example of a migration of the entity extended in this guide:
import { MigrationInterface, QueryRunner } from "typeorm"
class changeProduct1680013376180 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
"ALTER TABLE \"product\"" +
" ADD COLUMN \"customAttribute\" text"
)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
"ALTER TABLE \"product\" DROP COLUMN \"customAttribute\""
)
}
}
export default changeProduct1680013376180
Step 5: Use Custom Entity
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 migrate your changes to the database:
npx medusa migrations run
You should see that your migration was executed, which means your changes were reflected in the database schema.
You can now use your extended entity throughout your commerce application.
Access Custom Attributes and Relations in Core Endpoints
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.
To allow passing your custom attribute, you'll need to extend the validator of the endpoint.
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.
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.
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:
export default async function () {
const imports = (await import(
"@medusajs/medusa/dist/api/routes/store/products/index"
)) as any
imports.allowedStoreProductsFields = [
...imports.allowedStoreProductsFields,
"customAttribute",
]
imports.defaultStoreProductsFields = [
...imports.defaultStoreProductsFields,
"customAttribute",
]
}
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:
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 thefieldsrequest 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.
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.
:::tip
Before you test out the above change, make sure to build your changes before you start the Medusa backend.
:::
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 theexpandrequest 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.
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).
Advanced Entity Definitions
With entities, you can create relationships, index keys, and more. As Medusa uses Typeorm, you can learn about using these functionalities through Typeorm's documentation.