refactor: switch eslint configuration to strict type checking
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MikroOrmStorage.ts
1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { type Configuration, MikroORM, type Options } from '@mikro-orm/core'
4 import { TsMorphMetadataProvider } from '@mikro-orm/reflection'
5
6 import { Storage } from './Storage.js'
7 import {
8 type MikroOrmDbType,
9 PerformanceData,
10 PerformanceRecord,
11 type Statistics,
12 StorageType
13 } from '../../types/index.js'
14 import { Constants } from '../../utils/index.js'
15
16 export class MikroOrmStorage extends Storage {
17 private readonly storageType: StorageType
18 private orm?: MikroORM
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 == null) {
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 != null) {
48 await this.orm.close()
49 delete this.orm
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 this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '')
61 }
62
63 private getOptions (): Configuration | Options {
64 return {
65 metadataProvider: TsMorphMetadataProvider,
66 entities: [PerformanceRecord, PerformanceData],
67 type: this.storageType as MikroOrmDbType,
68 clientUrl: this.getClientUrl()
69 }
70 }
71
72 private getClientUrl (): string | undefined {
73 switch (this.storageType) {
74 case StorageType.SQLITE:
75 case StorageType.MARIA_DB:
76 case StorageType.MYSQL:
77 return this.storageUri.toString()
78 }
79 }
80 }