Files
medusa-store/docs/content/advanced/backend/entities/index.md
Shahed Nasser 589cb18f98 docs: improved SEO of documentation (#3117)
* docs: added description to documentation pages

* docs: added more descriptions

* docs: finished improving meta description

* docs: added searchbox structured data

* docs: added breadcrumbs structured data

* docs: added how to structured data

* docs: improved 404 page

* docs: added how-to frontmatter option
2023-01-26 15:58:33 +02:00

143 lines
5.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
description: 'Learn how to create an entity in the Medusa server. This guide also explains how to create a repository and access and delete the entity.'
addHowToData: true
---
# Create an Entity
In this document, youll learn how you can create an [Entity](overview.md).
## Create the Entity
To create an entity, create a TypeScript file in `src/models`. For example, heres a `Post` entity defined in the file `src/models/post.ts`:
```ts title=src/models/post.ts
import { BeforeInsert, Column, Entity, PrimaryColumn } from "typeorm"
import { BaseEntity } from "@medusajs/medusa"
import { generateEntityId } from "@medusajs/medusa/dist/utils"
@Entity()
export class Post extends BaseEntity {
@Column({ type: "varchar" })
title: string | null
@BeforeInsert()
private beforeInsert(): void {
this.id = generateEntityId(this.id, "post")
}
}
```
This entity has one column `title` defined. However, since it extends `BaseEntity` it will also have the `id`, `created_at`, and `updated_at` columns.
Medusas core entities all have the following format for IDs: `<PREFIX>_<RANDOM>`. For example, an order might have the ID `order_01G35WVGY4D1JCA4TPGVXPGCQM`.
To generate an ID for your entity that matches the IDs generated for Medusas core entities, you should add a `BeforeInsert` event handler. Then, inside that handler use Medusas utility function `generateEntityId` to generate the ID. It accepts the ID as a first parameter and the prefix as a second parameter. The `Post` entity IDs will be of the format `post_<RANDOM>`.
If you want the entity to also be soft deletable then it should extend `SoftDeletableEntity` instead:
```ts
import { SoftDeletableEntity } from "@medusajs/medusa"
@Entity()
export class Post extends SoftDeletableEntity {
// ...
}
```
You can learn more about what decorators and column types you can use in [Typeorms documentation](https://typeorm.io/entities).
### 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.md).
### 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, heres 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"
@EntityRepository(Post)
export class PostRepository extends Repository<Post> { }
```
This repository is created for the `Post` and that is indicated using the decorator `@EntityRepository`.
:::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.
:::
---
## Access a Custom Entity
:::note
Before trying this step make sure that youve created and run your migrations. You also need to re-build your code using:
```bash npm2yarn
npm run build
```
:::
You can access your custom entity data in the database in services or subscribers using the repository. For example, heres a service that lists all posts:
```ts
import { TransactionBaseService } from "@medusajs/medusa"
class PostService extends TransactionBaseService {
constructor({ postRepository, manager }) {
super({ postRepository, manager })
this.postRepository = postRepository
this.manager_ = manager
}
async list() {
const postRepository = this.manager_
.getCustomRepository(this.postRepository)
return await postRepository.find()
}
}
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.
After getting an instance of the repository, you can then use [Typeorms 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.
:::note
This same usage of repositories can be done in subscribers as well.
:::
### Delete a Soft-Deletable Entity
To delete soft-deletable entities that extend the `SoftDeletableEntity` class, you can use the repository method `softDelete` method:
```ts
await postRepository.softDelete(post.id)
```
---
## See Also
- [Entities' reference](../../../references/entities/classes/Address.md)
- [Migrations Overview](../migrations/overview.md)
- [Create a Services](../services/create-service.md)