1953491adb698692172c7595ac57e28016cc7360
[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 import { TsMorphMetadataProvider } from '@mikro-orm/reflection';
12
13 export class MikroOrmStorage extends Storage {
14 private storageType: StorageType;
15 private orm: MikroORM | null;
16
17 constructor(storageUri: string, logPrefix: string, storageType: StorageType) {
18 super(storageUri, logPrefix);
19 this.storageType = storageType;
20 this.dbName = this.getDBName();
21 }
22
23 public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> {
24 try {
25 const performanceRecord = new PerformanceRecord();
26 await this.orm.em.persistAndFlush(performanceRecord);
27 } catch (error) {
28 this.handleDBError(this.storageType, error as Error, Constants.PERFORMANCE_RECORDS_TABLE);
29 }
30 }
31
32 public async open(): Promise<void> {
33 try {
34 if (!this?.orm) {
35 this.orm = await MikroORM.init(this.getOptions(), true);
36 }
37 } catch (error) {
38 this.handleDBError(this.storageType, error as Error);
39 }
40 }
41
42 public async close(): Promise<void> {
43 try {
44 if (this?.orm) {
45 await this.orm.close();
46 this.orm = null;
47 }
48 } catch (error) {
49 this.handleDBError(this.storageType, error as Error);
50 }
51 }
52
53 private getDBName(): string {
54 if (this.storageType === StorageType.SQLITE) {
55 return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
56 }
57 return (
58 this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ??
59 Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
60 );
61 }
62
63 private getOptions():
64 | Configuration<IDatabaseDriver<Connection>>
65 | Options<IDatabaseDriver<Connection>> {
66 return {
67 metadataProvider: TsMorphMetadataProvider,
68 entities: [PerformanceRecord, PerformanceData],
69 type: this.storageType as MikroORMDBType,
70 clientUrl: this.getClientUrl(),
71 };
72 }
73
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();
80 }
81 }
82 }