Converted more procedural programming to OOP

This commit is contained in:
2024-12-26 23:34:25 +01:00
parent b7f448cb17
commit e571cf2230
46 changed files with 449 additions and 382 deletions

View File

@ -0,0 +1,18 @@
import { Request, Response } from 'express'
export abstract class BaseController {
protected sendSuccess(res: Response, data?: any, message?: string, status: number = 200) {
return res.status(status).json({
success: true,
message,
data
})
}
protected sendError(res: Response, message: string, status: number = 400) {
return res.status(status).json({
success: false,
message
})
}
}

View File

@ -0,0 +1,67 @@
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()
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 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
}
}
async delete(): Promise<this> {
try {
const orm = await Database.getInstance()
const em = orm.em.fork()
await em.begin()
try {
em.remove(this)
await em.flush()
await em.commit()
return this
} catch (error) {
await em.rollback()
throw error
}
} catch (error) {
appLogger.error(`Failed to remove entity: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
}
}

View File

@ -0,0 +1,24 @@
import { appLogger } from '../logger'
import { Database } from '../database'
import { EntityManager, MikroORM } from '@mikro-orm/core'
export abstract class BaseRepository {
protected orm!: MikroORM
protected em!: EntityManager
constructor() {
this.initializeORM().catch((error) => {
appLogger.error(`Failed to initialize Repository: ${error instanceof Error ? error.message : String(error)}`)
})
}
private async initializeORM() {
try {
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
}
}
}