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