1
0
forked from noxious/server

DB init. improvements

This commit is contained in:
Dennis Postma 2024-12-27 19:03:05 +01:00
parent 474683082d
commit bd85908014
4 changed files with 46 additions and 76 deletions

View File

@ -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' import { appLogger } from '#application/logger'
export abstract class BaseEntity { export abstract class BaseEntity {
async save(): Promise<this> { private getEntityManager(): EntityManager {
try { return Database.getEntityManager()
const orm = await Database.getInstance() }
const em = orm.em.fork()
await em.begin() async save(): Promise<this> {
try { return this.performDbOperation('persist', 'save entity')
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 update(): Promise<this> { async update(): Promise<this> {
try { return this.performDbOperation('merge', 'update entity')
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
}
} }
async delete(): Promise<this> { async delete(): Promise<this> {
return this.performDbOperation('remove', 'remove entity')
}
private async performDbOperation(method: 'persist' | 'merge' | 'remove', actionDescription: string): Promise<this> {
try { try {
const orm = await Database.getInstance() const em = this.getEntityManager()
const em = orm.em.fork()
await em.begin() await em.begin()
try { try {
em.remove(this) em[method](this)
await em.flush() await em.flush()
await em.commit() await em.commit()
return this return this
@ -60,8 +34,8 @@ export abstract class BaseEntity {
throw error throw error
} }
} catch (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 throw error
} }
} }
} }

View File

@ -1,25 +1,12 @@
import { EntityManager, MikroORM } from '@mikro-orm/core' import { EntityManager, MikroORM } from '@mikro-orm/core'
import Database from '../database'
import { Database } from '../database'
import { appLogger } from '../logger'
export abstract class BaseRepository { export abstract class BaseRepository {
protected orm!: MikroORM protected get orm(): MikroORM {
protected em!: EntityManager return Database.getORM()
constructor() {
this.initializeORM().catch((error) => {
appLogger.error(`Failed to initialize Repository: ${error instanceof Error ? error.message : String(error)}`)
})
} }
private async initializeORM() { protected get em(): EntityManager {
try { return Database.getEntityManager()
this.orm = await Database.getInstance()
this.em = this.orm.em.fork()
} catch (error: any) {
appLogger.error(`Failed to initialize ORM: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
} }
} }

View File

@ -1,28 +1,36 @@
// import { MikroORM } from '@mikro-orm/mariadb'
import { MikroORM } from '@mikro-orm/mysql' import { MikroORM } from '@mikro-orm/mysql'
import { EntityManager } from '@mikro-orm/core'
import { appLogger } from './logger' import { appLogger } from './logger'
import config from '../../mikro-orm.config' import config from '../../mikro-orm.config'
/** class Database {
* Singleton class for initializing and managing the database connection private static orm: MikroORM
*/ private static em: EntityManager
export class Database {
private static instance: MikroORM | undefined
private static async init(): Promise<MikroORM> { public static async initialize(): Promise<void> {
try { try {
return await MikroORM.init(config) Database.orm = await MikroORM.init(config)
Database.em = Database.orm.em.fork()
appLogger.info('Database connection initialized')
} catch (error) { } catch (error) {
appLogger.error(`MikroORM connection failed: ${error}`) appLogger.error(`MikroORM connection failed: ${error}`)
throw error throw error
} }
} }
public static async getInstance(): Promise<MikroORM> { public static getORM(): MikroORM {
if (!Database.instance) { if (!Database.orm) {
Database.instance = await Database.init() throw new Error('Database not initialized. Call Database.initialize() first.')
} }
return Database.instance return Database.orm
}
public static getEntityManager(): EntityManager {
if (!Database.em) {
throw new Error('Database not initialized. Call Database.initialize() first.')
}
return Database.em
} }
} }
export default Database

View File

@ -6,7 +6,7 @@ import express, { Application } from 'express'
import { Server as SocketServer } from 'socket.io' import { Server as SocketServer } from 'socket.io'
import config from '#application/config' import config from '#application/config'
import { Database } from '#application/database' import Database from '#application/database'
import { appLogger, watchLogs } from '#application/logger' import { appLogger, watchLogs } from '#application/logger'
import { getAppPath } from '#application/storage' import { getAppPath } from '#application/storage'
import { TSocket } from '#application/types' import { TSocket } from '#application/types'
@ -53,9 +53,10 @@ export class Server {
// Connect to database // Connect to database
try { try {
await Database.getInstance() await Database.initialize()
} catch (error: any) { } catch (error: any) {
appLogger.error(`Database connection failed: ${error.message}`) appLogger.error(`Database connection failed: ${error.message}`)
process.exit(1) // Exit if database connection fails
} }
// Start the server // Start the server