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