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