X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fperformance%2Fstorage%2FMikroORMStorage.ts;h=c06617f6253683f17065e90c9b7cba8cfa45eb20;hb=65334d061f549a3136373b27c35cb0e508c75a9f;hp=4d39dc7403beb97b3b46d24bbae4cb5198502a85;hpb=a6b3c6c313f1c0314a1445ed630cac85edf55b2c;p=e-mobility-charging-stations-simulator.git diff --git a/src/performance/storage/MikroORMStorage.ts b/src/performance/storage/MikroORMStorage.ts index 4d39dc74..c06617f6 100644 --- a/src/performance/storage/MikroORMStorage.ts +++ b/src/performance/storage/MikroORMStorage.ts @@ -8,15 +8,16 @@ import { PerformanceData } from '../../types/orm/entities/PerformanceData'; import { PerformanceRecord } from '../../types/orm/entities/PerformanceRecord'; import Statistics from '../../types/Statistics'; import { Storage } from './Storage'; +import { TsMorphMetadataProvider } from '@mikro-orm/reflection'; export class MikroORMStorage extends Storage { private storageType: StorageType; - private orm: MikroORM; + private orm: MikroORM | null; constructor(storageURI: string, logPrefix: string, storageType: StorageType) { super(storageURI, logPrefix); this.storageType = storageType; - this.dbName = this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; + this.dbName = this.getDBName(); } public async storePerformanceStatistics(performanceStatistics: Statistics): Promise { @@ -29,20 +30,49 @@ export class MikroORMStorage extends Storage { } public async open(): Promise { - this.orm = await MikroORM.init(this.getOptions(), true); + try { + if (!this?.orm) { + this.orm = await MikroORM.init(this.getOptions(), true); + } + } catch (error) { + this.handleDBError(this.storageType, error); + } } public async close(): Promise { - await this.orm.close(); + try { + if (this?.orm) { + await this.orm.close(); + this.orm = null; + } + } catch (error) { + this.handleDBError(this.storageType, error); + } + } + + private getDBName(): string { + if (this.storageType === StorageType.SQLITE) { + return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`; + } + return this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; } private getOptions(): Configuration> | Options> { return { + metadataProvider: TsMorphMetadataProvider, entities: [PerformanceRecord, PerformanceData], - dbName: this.dbName, type: this.storageType as MikroORMDBType, - clientUrl: this.storageURI.toString() + clientUrl: this.getClientUrl() }; } + + private getClientUrl(): string { + switch (this.storageType) { + case StorageType.SQLITE: + case StorageType.MARIA_DB: + case StorageType.MYSQL: + return this.storageURI.toString(); + } + } }