1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { type Configuration
, MikroORM
, type Options
} from
'@mikro-orm/core'
4 import { TsMorphMetadataProvider
} from
'@mikro-orm/reflection'
6 import { Storage
} from
'./Storage.js'
13 } from
'../../types/index.js'
14 import { Constants
} from
'../../utils/index.js'
16 export class MikroOrmStorage
extends Storage
{
17 private readonly storageType
: StorageType
18 private orm
?: MikroORM
20 constructor (storageUri
: string, logPrefix
: string, storageType
: StorageType
) {
21 super(storageUri
, logPrefix
)
22 this.storageType
= storageType
23 this.dbName
= this.getDBName()
26 public async storePerformanceStatistics (performanceStatistics
: Statistics
): Promise
<void> {
28 const performanceRecord
= new PerformanceRecord()
29 await this.orm
?.em
.persistAndFlush(performanceRecord
)
31 this.handleDBError(this.storageType
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
)
35 public async open (): Promise
<void> {
37 if (this.orm
== null) {
38 this.orm
= await MikroORM
.init(this.getOptions(), true)
41 this.handleDBError(this.storageType
, error
as Error)
45 public async close (): Promise
<void> {
47 if (this.orm
!= null) {
48 await this.orm
.close()
52 this.handleDBError(this.storageType
, error
as Error)
56 private getDBName (): string {
57 if (this.storageType
=== StorageType
.SQLITE
) {
58 return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`
60 return this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '')
63 private getOptions (): Configuration
| Options
{
65 metadataProvider
: TsMorphMetadataProvider
,
66 entities
: [PerformanceRecord
, PerformanceData
],
67 type: this.storageType
as MikroOrmDbType
,
68 clientUrl
: this.getClientUrl()
72 private getClientUrl (): string | undefined {
73 switch (this.storageType
) {
74 case StorageType
.SQLITE
:
75 case StorageType
.MARIA_DB
:
76 case StorageType
.MYSQL
:
77 return this.storageUri
.toString()