57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import { EntityManager } from '@mikro-orm/core'
|
|
|
|
import Database from '#application/database'
|
|
import Logger, { LoggerType } from '#application/logger'
|
|
|
|
export abstract class BaseEntity {
|
|
protected readonly logger = Logger.type(LoggerType.ENTITY)
|
|
protected entityManager?: EntityManager
|
|
|
|
private getEntityManager(): EntityManager {
|
|
if (!this.entityManager) {
|
|
this.entityManager = Database.getORM().em.fork()
|
|
}
|
|
return this.entityManager
|
|
}
|
|
|
|
public setEntityManager(entityManager: EntityManager) {
|
|
this.entityManager = entityManager
|
|
return this
|
|
}
|
|
|
|
async save(): Promise<this> {
|
|
return this.execute('persist', 'save entity')
|
|
}
|
|
|
|
async delete(): Promise<this> {
|
|
return this.execute('remove', 'remove entity')
|
|
}
|
|
|
|
async update(): Promise<this> {
|
|
return this.execute('merge', 'update entity')
|
|
}
|
|
|
|
private async execute(method: 'persist' | 'merge' | 'remove', actionDescription: string): Promise<this> {
|
|
try {
|
|
const em = this.getEntityManager()
|
|
|
|
await em.begin()
|
|
try {
|
|
em[method](this)
|
|
await em.flush()
|
|
await em.commit()
|
|
return this
|
|
} catch (error) {
|
|
await em.rollback()
|
|
throw error
|
|
}
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : error && typeof error === 'object' && 'toString' in error ? error.toString() : String(error)
|
|
|
|
console.log(errorMessage)
|
|
this.logger.error(`Failed to ${actionDescription}: ${errorMessage}`)
|
|
throw error
|
|
}
|
|
}
|
|
}
|