Skip to main content

Create an Entity

In this document, you’ll learn how you can create an Entity.

Create the Entity

To create an entity, create a TypeScript file in src/modelsCopy to Clipboard. For example, here’s a PostCopy to Clipboard entity defined in the file src/models/post.tsCopy to Clipboard:

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")
}
}
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

This entity has one column titleCopy to Clipboard defined. However, since it extends BaseEntityCopy to Clipboard it will also have the idCopy to Clipboard, created_atCopy to Clipboard, and updated_atCopy to Clipboard columns.

Medusa’s core entities all have the following format for IDs: <PREFIX>_<RANDOM>Copy to Clipboard. For example, an order might have the ID order_01G35WVGY4D1JCA4TPGVXPGCQMCopy to Clipboard.

To generate an ID for your entity that matches the IDs generated for Medusa’s core entities, you should add a BeforeInsertCopy to Clipboard event handler. Then, inside that handler use Medusa’s utility function generateEntityIdCopy to Clipboard to generate the ID. It accepts the ID as a first parameter and the prefix as a second parameter. The PostCopy to Clipboard entity IDs will be of the format post_<RANDOM>Copy to Clipboard.

If you want the entity to also be soft deletable then it should extend SoftDeletableEntityCopy to Clipboard instead:

import { SoftDeletableEntity } from "@medusajs/medusa"

@Entity()
export class Post extends SoftDeletableEntity {
// ...
}
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

You can learn more about what decorators and column types you can use in Typeorm’s documentation.

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.

Create a Repository

Entities data can be easily accessed and modified using Typeorm Repositories. To create a repository, create a file in src/repositoriesCopy to Clipboard. For example, here’s a repository PostRepositoryCopy to Clipboard created in src/repositories/post.tsCopy to Clipboard:

src/repositories/post.ts
import { EntityRepository, Repository } from "typeorm"

import { Post } from "../models/post"

@EntityRepository(Post)
export class PostRepository extends Repository<Post> { }
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

This repository is created for the PostCopy to Clipboard and that is indicated using the decorator @EntityRepositoryCopy to Clipboard.

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

Before trying this step make sure that you’ve created and run your migrations. You also need to re-build your code using:

yarn run build
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

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:

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
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

In the constructor, you can use dependency injection to get access to instances of services and repositories. Here, you initialize class fields postRepositoryCopy to Clipboard and managerCopy to Clipboard. The managerCopy to Clipboard is a Typeorm Entity Manager.

Then, in the method listCopy to Clipboard, you can obtain an instance of the PostRepositoryCopy to Clipboard using this.manager_.getCustomRepositoryCopy to Clipboard passing it this.postRepositoryCopy to Clipboard as a parameter. This lets you use Custom Repositories with Typeorm 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 Typeorm’s Repository methods 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.

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 SoftDeletableEntityCopy to Clipboard class, you can use the repository method softDeleteCopy to Clipboard method:

await postRepository.softDelete(post.id)
Report Incorrect CodeReport Incorrect CodeCopy to ClipboardCopy to Clipboard

See Also