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