6afb820399e32d2d47f400d4f79a7bcd27cfe017
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MikroORMStorage.ts
1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { Configuration, Connection, IDatabaseDriver, MikroORM, Options } from '@mikro-orm/core';
4 import { MikroORMDBType, StorageType } from '../../types/Storage';
5
6 import Constants from '../../utils/Constants';
7 import { PerformanceData } from '../../types/orm/entities/PerformanceData';
8 import { PerformanceRecord } from '../../types/orm/entities/PerformanceRecord';
9 import Statistics from '../../types/Statistics';
10 import { Storage } from './Storage';
11
12 export class MikroORMStorage extends Storage {
13 private storageType: StorageType;
14 private orm: MikroORM;
15
16 constructor(storageURI: string, logPrefix: string, storageType: StorageType) {
17 super(storageURI, logPrefix);
18 this.storageType = storageType;
19 this.dbName = this.getDBName();
20 }
21
22 public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> {
23 try {
24 const performanceRecord = new PerformanceRecord();
25 await this.orm.em.persistAndFlush(performanceRecord);
26 } catch (error) {
27 this.handleDBError(this.storageType, error, Constants.PERFORMANCE_RECORDS_TABLE);
28 }
29 }
30
31 public async open(): Promise<void> {
32 this.orm = await MikroORM.init(this.getOptions(), true);
33 }
34
35 public async close(): Promise<void> {
36 await this.orm.close();
37 }
38
39 private getDBName(): string {
40 if (this.storageType === StorageType.SQLITE) {
41 return Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME;
42 }
43 return this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME;
44 }
45
46 private getOptions(): Configuration<IDatabaseDriver<Connection>> | Options<IDatabaseDriver<Connection>> {
47 return {
48 entities: [PerformanceRecord, PerformanceData],
49 dbName: this.dbName,
50 type: this.storageType as MikroORMDBType,
51 clientUrl: this.getClientUrl()
52 };
53 }
54
55 private getClientUrl(): string {
56 switch (this.storageType) {
57 case StorageType.SQLITE:
58 return this.storageURI.pathname;
59 case StorageType.MARIA_DB:
60 case StorageType.MYSQL:
61 return this.storageURI.toString();
62 }
63 }
64 }
65