1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { Configuration
, Connection
, IDatabaseDriver
, MikroORM
, Options
} from
'@mikro-orm/core';
4 import { TsMorphMetadataProvider
} from
'@mikro-orm/reflection';
6 import { PerformanceData
} from
'../../types/orm/entities/PerformanceData';
7 import { PerformanceRecord
} from
'../../types/orm/entities/PerformanceRecord';
8 import Statistics from
'../../types/Statistics';
9 import { MikroORMDBType
, StorageType
} from
'../../types/Storage';
10 import Constants from
'../../utils/Constants';
11 import { Storage
} from
'./Storage';
13 export class MikroOrmStorage
extends Storage
{
14 private storageType
: StorageType
;
15 private orm
: MikroORM
| null;
17 constructor(storageUri
: string, logPrefix
: string, storageType
: StorageType
) {
18 super(storageUri
, logPrefix
);
19 this.storageType
= storageType
;
20 this.dbName
= this.getDBName();
23 public async storePerformanceStatistics(performanceStatistics
: Statistics
): Promise
<void> {
25 const performanceRecord
= new PerformanceRecord();
26 await this.orm
.em
.persistAndFlush(performanceRecord
);
28 this.handleDBError(this.storageType
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
);
32 public async open(): Promise
<void> {
35 this.orm
= await MikroORM
.init(this.getOptions(), true);
38 this.handleDBError(this.storageType
, error
as Error);
42 public async close(): Promise
<void> {
45 await this.orm
.close();
49 this.handleDBError(this.storageType
, error
as Error);
53 private getDBName(): string {
54 if (this.storageType
=== StorageType
.SQLITE
) {
55 return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
58 this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '') ??
59 Constants
.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
64 | Configuration
<IDatabaseDriver
<Connection
>>
65 | Options
<IDatabaseDriver
<Connection
>> {
67 metadataProvider
: TsMorphMetadataProvider
,
68 entities
: [PerformanceRecord
, PerformanceData
],
69 type: this.storageType
as MikroORMDBType
,
70 clientUrl
: this.getClientUrl(),
74 private getClientUrl(): string {
75 switch (this.storageType
) {
76 case StorageType
.SQLITE
:
77 case StorageType
.MARIA_DB
:
78 case StorageType
.MYSQL
:
79 return this.storageUri
.toString();