43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import { EntityManager } from '@mikro-orm/core'
|
|
|
|
import Database from '#application/database'
|
|
import { appLogger } from '#application/logger'
|
|
|
|
export abstract class BaseEntity {
|
|
private getEntityManager(): EntityManager {
|
|
return Database.getEntityManager()
|
|
}
|
|
|
|
async save(): Promise<this> {
|
|
return this.execute('persist', 'save entity')
|
|
}
|
|
|
|
async update(): Promise<this> {
|
|
return this.execute('merge', 'update entity')
|
|
}
|
|
|
|
async delete(): Promise<this> {
|
|
return this.execute('remove', 'remove 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) {
|
|
appLogger.error(`Failed to ${actionDescription}: ${error instanceof Error ? error.message : String(error)}`)
|
|
throw error
|
|
}
|
|
}
|
|
}
|