Skip to content

Commit

Permalink
refactor: optimize the database connection creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Bastien Gatellier committed Jul 2, 2023
1 parent 2c5b522 commit a0e6728
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions modules/mysql/src/MySQLModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,37 @@ import { MikroORM } from "@mikro-orm/core"
import { type MySqlDriver } from "@mikro-orm/mysql"
import databaseConfig from "./config/mikro-orm.config.js"

function createDatabaseClient(): Promise<MikroORM> {
return MikroORM.init<MySqlDriver>(databaseConfig)
}

export class MySQLModule extends Module implements ModuleListenerDatabaseInterface {
#orm: Promise<MikroORM<MySqlDriver>> | undefined

public async hasPendingMigrations(): Promise<boolean> {
const orm = await createDatabaseClient()
const orm = await this.getOrCreateDatabaseClient()
const migrator = orm.getMigrator()

const migrations = await migrator.getPendingMigrations()

await orm.close(true)

return migrations.length > 0
}

public async runPendingMigrations(): Promise<void> {
const orm = await createDatabaseClient()
const orm = await this.getOrCreateDatabaseClient()
const migrator = orm.getMigrator()

await migrator.up()

return orm.close(true)
}

public async notifyAnalysisDone(report: GenericReport<Result>): Promise<void> {
const orm = await createDatabaseClient()
const orm = await this.getOrCreateDatabaseClient()
const reportEntity = new ReportEntity<Result>(report)

await orm.em.persistAndFlush(reportEntity)

return orm.close(true)
console.log("entity persisted and flushed")

return orm.close()
}

private async getOrCreateDatabaseClient(): Promise<MikroORM<MySqlDriver>> {
return this.#orm ?? MikroORM.init<MySqlDriver>(databaseConfig)
}
}

0 comments on commit a0e6728

Please sign in to comment.