docs: add documentation for v1.8 (#3669)
This commit is contained in:
@@ -3,11 +3,11 @@ description: 'Learn how to create an entity in Medusa. This guide also explains
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
# Create an Entity
|
||||
# How to Create an Entity
|
||||
|
||||
In this document, you’ll learn how you can create an [Entity](./overview.mdx).
|
||||
In this document, you’ll learn how you can create a custom [Entity](./overview.mdx).
|
||||
|
||||
## Create the Entity
|
||||
## Step 1: Create the Entity
|
||||
|
||||
To create an entity, create a TypeScript file in `src/models`. For example, here’s a `Post` entity defined in the file `src/models/post.ts`:
|
||||
|
||||
@@ -52,46 +52,85 @@ export class Post extends SoftDeletableEntity {
|
||||
|
||||
You can learn more about what decorators and column types you can use in [Typeorm’s documentation](https://typeorm.io/entities).
|
||||
|
||||
### Create a Migration
|
||||
---
|
||||
|
||||
## Step 2: Create a Migration
|
||||
|
||||
Additionally, you must create a migration for your entity. Migrations are used to update the database schema with new tables or changes to existing tables.
|
||||
|
||||
You can learn more about Migrations, how to create them, and how to run them in the [Migration documentation](./migrations/overview.mdx).
|
||||
You can learn more about Migrations, how to create or generate them, and how to run them in the [Migration documentation](./migrations/overview.mdx).
|
||||
|
||||
### Create a Repository
|
||||
---
|
||||
|
||||
## Step 3: Create a Repository
|
||||
|
||||
Entities data can be easily accessed and modified using Typeorm [Repositories](https://typeorm.io/working-with-repository). To create a repository, create a file in `src/repositories`. For example, here’s a repository `PostRepository` created in `src/repositories/post.ts`:
|
||||
|
||||
```ts title=src/repositories/post.ts
|
||||
import { EntityRepository, Repository } from "typeorm"
|
||||
|
||||
import { Post } from "../models/post"
|
||||
import {
|
||||
dataSource,
|
||||
} from "@medusajs/medusa/dist/loaders/database"
|
||||
|
||||
@EntityRepository(Post)
|
||||
export class PostRepository extends Repository<Post> { }
|
||||
export const PostRepository = dataSource
|
||||
.getRepository(Post)
|
||||
|
||||
export default PostRepository
|
||||
```
|
||||
|
||||
This repository is created for the `Post` and that is indicated using the decorator `@EntityRepository`.
|
||||
The repository is created using the `getRepository` method of the data source exported from the core package in Medusa. This method accepts the entity as a parameter.
|
||||
|
||||
:::tip
|
||||
|
||||
Be careful with your file names as it can cause unclear errors in Typeorm. Make sure all your file names are small letters for both entities and repositories to avoid any issues with file names.
|
||||
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](https://typeorm.io/data-source).
|
||||
|
||||
:::
|
||||
|
||||
If you want to add methods to that repository or override Typeorm's Repository methods, you can do that using the `extend` method:
|
||||
|
||||
```ts title=src/repositories/post.ts
|
||||
import { Post } from "../models/post"
|
||||
import {
|
||||
dataSource,
|
||||
} from "@medusajs/medusa/dist/loaders/database"
|
||||
|
||||
export const PostRepository = dataSource
|
||||
.getRepository(Post)
|
||||
.extend({
|
||||
customFunction(): void {
|
||||
// TODO add custom implementation
|
||||
return
|
||||
},
|
||||
})
|
||||
|
||||
export default PostRepository
|
||||
```
|
||||
|
||||
You can learn about available Repository methods in [Typeorm's documentation](https://typeorm.io/repository-api).
|
||||
|
||||
---
|
||||
|
||||
## Access a Custom Entity
|
||||
## Step 4: Run Migrations
|
||||
|
||||
:::note
|
||||
Before you start using your entity, make sure to run the migrations that reflect the entity on your database schema.
|
||||
|
||||
Before trying this step make sure that you’ve created and run your migrations. You also need to re-build your code using:
|
||||
To do that, run the `build` command that transpiles your code:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
:::
|
||||
Then, run the `migration` command:
|
||||
|
||||
```bash npm2yarn
|
||||
medusa migrations run
|
||||
```
|
||||
|
||||
You should see that your migration have executed.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Use Your Entity
|
||||
|
||||
You can access your custom entity data in the database in services or subscribers using the repository. For example, here’s a service that lists all posts:
|
||||
|
||||
@@ -107,9 +146,9 @@ class PostService extends TransactionBaseService {
|
||||
}
|
||||
|
||||
async list() {
|
||||
const postRepository = this.manager_
|
||||
.getCustomRepository(this.postRepository)
|
||||
return await postRepository.find()
|
||||
const postRepo = this.manager_
|
||||
.withRepository(this.postRepository)
|
||||
return await postRepo.find()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,15 +157,13 @@ export default PostService
|
||||
|
||||
In the constructor, you can use dependency injection to get access to instances of services and repositories. Here, you initialize class fields `postRepository` and `manager`. The `manager` is a [Typeorm Entity Manager](https://typeorm.io/working-with-entity-manager).
|
||||
|
||||
Then, in the method `list`, you can obtain an instance of the `PostRepository` using `this.manager_.getCustomRepository` passing it `this.postRepository` as a parameter. This lets you use [Custom Repositories with Typeorm](https://typeorm.io/custom-repository) to create custom methods in your repository that work with the data in your database.
|
||||
Then, in the method `list`, you can create an instance of the `PostRepository` using the `this.manager_.withRepository` method passing it `this.postRepository` as a parameter.
|
||||
|
||||
After getting an instance of the repository, you can then use [Typeorm’s Repository methods](https://typeorm.io/repository-api) to perform Create, Read, Update, and Delete (CRUD) operations on your entity.
|
||||
|
||||
If you need access to your entity in endpoints, you can then use the methods you define in the service.
|
||||
After getting an instance of the repository, you can then use [Typeorm’s Repository methods](https://typeorm.io/repository-api) to perform Create, Read, Update, and Delete (CRUD) operations on your entity. You can also use any custom methods that you defined in the Repository.
|
||||
|
||||
:::note
|
||||
|
||||
This same usage of repositories can be done in subscribers as well.
|
||||
This same usage of repositories can be done in other resources such as subscribers or endpoints.
|
||||
|
||||
:::
|
||||
|
||||
@@ -142,5 +179,5 @@ await postRepository.softDelete(post.id)
|
||||
|
||||
## See Also
|
||||
|
||||
- [Migrations Overview](./migrations/overview.mdx)
|
||||
- [Extend Entity](./extend-entity.md)
|
||||
- [Create a Plugin](../plugins/create.md)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
description: 'Learn how to extend a core entity in Medusa to add custom attributes.'
|
||||
addHowToData: 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:
|
||||
|
||||
```ts title=src/models/product.ts
|
||||
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:
|
||||
|
||||
```ts title=src/index.d.ts
|
||||
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: Extend Repository
|
||||
|
||||
As the entity is used throughout the commerce application through its repository, the core package will not actually be aware that the entity was extended unless you also extend the repository.
|
||||
|
||||
The steps here are similar to those described in the [How to Extend a Repository documentation](./extend-repository.md), however, the implementation is a little different.
|
||||
|
||||
Start by creating the repository file `src/repositories/product.ts`. As mentioned in the repository documentation, the name of the file should be the same as the name in the core. So, if you’re extending another repository, use the file name of that repository instead.
|
||||
|
||||
Then, in the file, add the following content:
|
||||
|
||||
```ts title=src/repositories/product.ts
|
||||
import { Product } from "../models/product"
|
||||
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.
|
||||
// you also update the target to the extended entity
|
||||
...Object.assign(
|
||||
MedusaProductRepository,
|
||||
{ target: Product }
|
||||
),
|
||||
|
||||
// you can add other customizations as well...
|
||||
})
|
||||
|
||||
export default ProductRepository
|
||||
```
|
||||
|
||||
Instead of just spreading the properties of the `MedusaProductRepository` as you did when extending a repository, you have to change the value of the `target` property to be the entity you created.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: 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](./migrations/create.md).
|
||||
|
||||
Here’s an example of a migration of the entity extended in this guide:
|
||||
|
||||
```ts title=src/migration/1680013376180-changeProduct.ts
|
||||
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 6: 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:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
Then, run the following command to migrate your changes to the database:
|
||||
|
||||
```bash npm2yarn
|
||||
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 and its repository throughout your commerce application.
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
description: 'Learn how to extend a core repository in Medusa to add custom methods.'
|
||||
addHowToData: 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](https://typeorm.io/data-source).
|
||||
|
||||
:::
|
||||
|
||||
Here’s an example of the implementation of the extended Product repository:
|
||||
|
||||
```ts title=src/repositories/product.ts
|
||||
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:
|
||||
|
||||
```ts
|
||||
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:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
Then, run the following command to start your backend:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run start
|
||||
```
|
||||
|
||||
You should see your custom implementation working as expected.
|
||||
@@ -22,36 +22,29 @@ The migration file must be inside the `src/migrations` directory. When you run t
|
||||
<details>
|
||||
<summary>Generating Migrations for Entities</summary>
|
||||
|
||||
You can alternatively use Typeorm's `generate` command to generate a Migration file from existing entity classes. As Medusa uses v0.2.45 of Typeorm, you have to create a `ormconfig.json` first before using the `generate` command.
|
||||
You can alternatively use Typeorm's `generate` command to generate a Migration file from existing entity classes. As of v1.8, Medusa uses Typeorm v0.3.x. You have to create a [DataSource](https://typeorm.io/data-source) first before using the `migration:generate` command.
|
||||
|
||||
:::note
|
||||
For example, create the file `datasource.js` in the root of your Medusa server with the following content:
|
||||
|
||||
Typeorm will be updated to the latest version in v1.8.0 of Medusa.
|
||||
|
||||
:::
|
||||
|
||||
For example, create the file `ormconfig.json` in the root of your Medusa server with the following content:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "postgres",
|
||||
"host": "localhost",
|
||||
"port": 5432,
|
||||
"username": "<YOUR_DB_USERNAME>",
|
||||
"password": "<YOUR_DB_PASSWORD>",
|
||||
"database": "<YOUR_DB_NAME>",
|
||||
"synchronize": true,
|
||||
"logging": false,
|
||||
"entities": [
|
||||
"dist/models/**/*.js"
|
||||
```js
|
||||
const { DataSource } = require("typeorm")
|
||||
|
||||
const AppDataSource = new DataSource({
|
||||
type: "postgres",
|
||||
port: 5432,
|
||||
username: "<YOUR_DB_USERNAME>",
|
||||
password: "<YOUR_DB_PASSWORD>",
|
||||
database: "<YOUR_DB_NAME>",
|
||||
entities: [
|
||||
"dist/models/*.js",
|
||||
],
|
||||
"migrations": [
|
||||
"dist/migrations/**/*.js"
|
||||
migrations: [
|
||||
"dist/migrations/*.js",
|
||||
],
|
||||
"cli": {
|
||||
"entitiesDir": "src/models",
|
||||
"migrationsDir": "src/migrations"
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = {
|
||||
datasource: AppDataSource,
|
||||
}
|
||||
```
|
||||
|
||||
@@ -66,7 +59,7 @@ Typeorm will be updated to the latest version in v1.8.0 of Medusa.
|
||||
Finally, run the following command to generate a Migration for your new entity:
|
||||
|
||||
```bash
|
||||
npx typeorm@0.2.45 migration:generate -n PostCreate
|
||||
npx typeorm migration:generate -d datasource.js src/migrations/PostCreate
|
||||
```
|
||||
|
||||
Where `PostCreate` is just an example of the name of the migration to generate. The migration will then be generated in `src/migrations/<TIMESTAMP>-PostCreate.ts`. You can then skip to step 3 of this guide.
|
||||
|
||||
@@ -76,10 +76,10 @@ Developers can create custom entities in the Medusa backend, a plugin, or in a C
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/entities/create',
|
||||
label: 'Create an Endpoint',
|
||||
label: 'Create an Entity',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create endpoints in Medusa.'
|
||||
description: 'Learn how to create an entity in Medusa.'
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -91,4 +91,22 @@ Developers can create custom entities in the Medusa backend, a plugin, or in a C
|
||||
description: 'Learn how to create migrations in Medusa.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/entities/extend-entity',
|
||||
label: 'Extend an Entity',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to extend a core Medusa entity.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/entities/extend-repository',
|
||||
label: 'Extend a Repository',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to extend a core Medusa repository.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
Reference in New Issue
Block a user