forked from noxious/server
DB init. improvements
This commit is contained in:
@ -1,57 +1,31 @@
|
||||
import { Database } from '#application/database'
|
||||
import { EntityManager } from '@mikro-orm/core'
|
||||
import Database from '#application/database'
|
||||
import { appLogger } from '#application/logger'
|
||||
|
||||
export abstract class BaseEntity {
|
||||
async save(): Promise<this> {
|
||||
try {
|
||||
const orm = await Database.getInstance()
|
||||
const em = orm.em.fork()
|
||||
private getEntityManager(): EntityManager {
|
||||
return Database.getEntityManager()
|
||||
}
|
||||
|
||||
await em.begin()
|
||||
try {
|
||||
em.persist(this)
|
||||
await em.flush()
|
||||
await em.commit()
|
||||
return this
|
||||
} catch (error) {
|
||||
await em.rollback()
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
appLogger.error(`Failed to save entity: ${error instanceof Error ? error.message : String(error)}`)
|
||||
throw error
|
||||
}
|
||||
async save(): Promise<this> {
|
||||
return this.performDbOperation('persist', 'save entity')
|
||||
}
|
||||
|
||||
async update(): Promise<this> {
|
||||
try {
|
||||
const orm = await Database.getInstance()
|
||||
const em = orm.em.fork()
|
||||
|
||||
await em.begin()
|
||||
try {
|
||||
em.merge(this)
|
||||
await em.flush()
|
||||
await em.commit()
|
||||
return this
|
||||
} catch (error) {
|
||||
await em.rollback()
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
appLogger.error(`Failed to update entity: ${error instanceof Error ? error.message : String(error)}`)
|
||||
throw error
|
||||
}
|
||||
return this.performDbOperation('merge', 'update entity')
|
||||
}
|
||||
|
||||
async delete(): Promise<this> {
|
||||
return this.performDbOperation('remove', 'remove entity')
|
||||
}
|
||||
|
||||
private async performDbOperation(method: 'persist' | 'merge' | 'remove', actionDescription: string): Promise<this> {
|
||||
try {
|
||||
const orm = await Database.getInstance()
|
||||
const em = orm.em.fork()
|
||||
const em = this.getEntityManager()
|
||||
|
||||
await em.begin()
|
||||
try {
|
||||
em.remove(this)
|
||||
em[method](this)
|
||||
await em.flush()
|
||||
await em.commit()
|
||||
return this
|
||||
@ -60,8 +34,8 @@ export abstract class BaseEntity {
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
appLogger.error(`Failed to remove entity: ${error instanceof Error ? error.message : String(error)}`)
|
||||
appLogger.error(`Failed to ${actionDescription}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user