refactor: make storage init compliant with MikroORM 6
[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 { Storage } from './Storage.js'
7 import { type Statistics, StorageType } from '../../types/index.js'
8 import { Constants } from '../../utils/index.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 // TODO: build PerformanceRecord entity
23 await this.orm?.em.persistAndFlush({})
24 } catch (error) {
25 this.handleDBError(this.storageType, error as Error, Constants.PERFORMANCE_RECORDS_TABLE)
26 }
27 }
28
29 public async open (): Promise<void> {
30 try {
31 if (this.orm == null) {
32 switch (this.storageType) {
33 case StorageType.SQLITE:
34 this.orm = await SqliteORM.init(this.getOptions() as SqliteOptions)
35 break
36 case StorageType.MARIA_DB:
37 case StorageType.MYSQL:
38 this.orm = await MariaDbORM.init(this.getOptions() as MariaDbOptions)
39 break
40 }
41 }
42 } catch (error) {
43 this.handleDBError(this.storageType, error as Error)
44 }
45 }
46
47 public async close (): Promise<void> {
48 try {
49 if (this.orm != null) {
50 await this.orm.close()
51 delete this.orm
52 }
53 } catch (error) {
54 this.handleDBError(this.storageType, error as Error)
55 }
56 }
57
58 private getDBName (): string {
59 if (this.storageType === StorageType.SQLITE) {
60 return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`
61 }
62 return this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '')
63 }
64
65 private getOptions (): SqliteOptions | MariaDbOptions {
66 return {
67 dbName: this.dbName,
68 entities: ['./dist/types/orm/entities/*.js'],
69 entitiesTs: ['./src/types/orm/entities/*.ts'],
70 clientUrl: this.getClientUrl()
71 }
72 }
73
74 private getClientUrl (): string | undefined {
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 }