Skip to content

Commit

Permalink
chore(utils): Provide a mikro orm base entity (medusajs#7286)
Browse files Browse the repository at this point in the history
**What**
Provide a new mikro orm base entity in order to abstract away the on init and on create which include the id auto generation if not provided. The main goal is to reduce complexity in entity definition
  • Loading branch information
adrien2p authored May 10, 2024
1 parent 144e09e commit 45e2228
Show file tree
Hide file tree
Showing 6 changed files with 204 additions and 37 deletions.
5 changes: 5 additions & 0 deletions .changeset/old-candles-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@medusajs/utils": patch
---

chore(utils): Provide a mikro orm base entity
2 changes: 1 addition & 1 deletion packages/core/utils/src/dal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export * from "./mikro-orm/mikro-orm-free-text-search-filter"
export * from "./mikro-orm/mikro-orm-repository"
export * from "./mikro-orm/mikro-orm-soft-deletable-filter"
export * from "./mikro-orm/mikro-orm-serializer"
export * from "./mikro-orm/base-entity"
export * from "./mikro-orm/utils"
export * from "./mikro-orm/decorators/searchable"
export * from "./repositories"
export * from "./utils"
130 changes: 130 additions & 0 deletions packages/core/utils/src/dal/mikro-orm/__tests__/base-entity.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { Entity, MikroORM, OnInit, Property } from "@mikro-orm/core"
import { BaseEntity } from "../base-entity"

describe("BaseEntity", () => {
it("should handle the id generation using the provided prefix", async () => {
@Entity()
class Entity1 extends BaseEntity {
constructor() {
super({ prefix_id: "prod" })
}
}

const orm = await MikroORM.init({
entities: [Entity1],
dbName: "test",
type: "postgresql",
})

const manager = orm.em.fork()
const entity1 = manager.create(Entity1, {})

expect(entity1.id).toMatch(/prod_[0-9]/)

await orm.close()
})

it("should handle the id generation without a provided prefix using the first three letter of the entity lower cased", async () => {
@Entity()
class Entity1 extends BaseEntity {}

const orm = await MikroORM.init({
entities: [Entity1],
dbName: "test",
type: "postgresql",
})

const manager = orm.em.fork()
const entity1 = manager.create(Entity1, {})

expect(entity1.id).toMatch(/ent_[0-9]/)

await orm.close()
})

it("should handle the id generation without a provided prefix inferring it based on the words composing the entity name excluding model and entity as part of the name", async () => {
@Entity()
class ProductModel extends BaseEntity {}

@Entity()
class ProductCategoryEntity extends BaseEntity {}

@Entity()
class ProductOptionValue extends BaseEntity {}

const orm = await MikroORM.init({
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
dbName: "test",
type: "postgresql",
})

const manager = orm.em.fork()

const product = manager.create(ProductModel, {})
const productCategory = manager.create(ProductCategoryEntity, {})
const productOptionValue = manager.create(ProductOptionValue, {})

expect(product.id).toMatch(/pro_[0-9]/)
expect(productCategory.id).toMatch(/prc_[0-9]/)
expect(productOptionValue.id).toMatch(/pov_[0-9]/)

await orm.close()
})

it("should handle the id generation even with custom onInit or beforeCreate", async () => {
@Entity()
class ProductModel extends BaseEntity {
@Property()
custom_prop: string

@OnInit()
onInit() {
this.custom_prop = "custom"
}
}

@Entity()
class ProductCategoryEntity extends BaseEntity {
@Property()
custom_prop: string

@OnInit()
onInit() {
this.custom_prop = "custom"
}
}

@Entity()
class ProductOptionValue extends BaseEntity {
@Property()
custom_prop: string

@OnInit()
onInit() {
this.custom_prop = "custom"
}
}

const orm = await MikroORM.init({
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
dbName: "test",
type: "postgresql",
})

const manager = orm.em.fork()

const product = manager.create(ProductModel, {})
const productCategory = manager.create(ProductCategoryEntity, {})
const productOptionValue = manager.create(ProductOptionValue, {})

expect(product.id).toMatch(/pro_[0-9]/)
expect(productCategory.id).toMatch(/prc_[0-9]/)
expect(productOptionValue.id).toMatch(/pov_[0-9]/)

expect(product.custom_prop).toBe("custom")
expect(productCategory.custom_prop).toBe("custom")
expect(productOptionValue.custom_prop).toBe("custom")

await orm.close()
})
})
68 changes: 68 additions & 0 deletions packages/core/utils/src/dal/mikro-orm/base-entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {
BeforeCreate,
Entity,
OnInit,
OptionalProps,
PrimaryKey,
} from "@mikro-orm/core"
import { generateEntityId } from "../../common"

@Entity({ abstract: true })
export class BaseEntity {
[OptionalProps]?: BaseEntity["id"] | BaseEntity["__prefix_id__"]

private __prefix_id__?: string

constructor({ prefix_id }: { prefix_id?: string } = {}) {
this.__prefix_id__ = prefix_id
}

@PrimaryKey({ columnType: "text" })
id!: string

@OnInit()
@BeforeCreate()
onInitOrBeforeCreate_() {
this.id ??= this.generateEntityId(this.__prefix_id__)
}

private generateEntityId(prefixId?: string): string {
if (prefixId) {
return generateEntityId(undefined, prefixId)
}

let ensuredPrefixId = Object.getPrototypeOf(this).constructor.name as string

/*
* Split the class name (camel case) into words and exclude model and entity from the words
*/
const words = ensuredPrefixId
.split(/(?=[A-Z])/)
.filter((word) => !["entity", "model"].includes(word.toLowerCase()))
const wordsLength = words.length

/*
* if the class name (camel case) contains one word, the prefix id is the first three letters of the word
* if the class name (camel case) contains two words, the prefix id is the first two letters of the first word plus the first letter of the second one
* if the class name (camel case) contains more than two words, the prefix id is the first letter of each word
*/
if (wordsLength === 1) {
ensuredPrefixId = words[0].substring(0, 3)
} else if (wordsLength === 2) {
ensuredPrefixId = words
.map((word, index) => {
return word.substring(0, 2 - index)
})
.join("")
} else {
ensuredPrefixId = words
.map((word) => {
return word[0]
})
.join("")
}

this.__prefix_id__ = ensuredPrefixId.toLowerCase()
return generateEntityId(undefined, this.__prefix_id__)
}
}
1 change: 0 additions & 1 deletion packages/core/utils/src/dal/repositories/index.ts

This file was deleted.

This file was deleted.

0 comments on commit 45e2228

Please sign in to comment.