Apply dependencies update
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MikroORMStorage.ts
index 6afb820399e32d2d47f400d4f79a7bcd27cfe017..c06617f6253683f17065e90c9b7cba8cfa45eb20 100644 (file)
@@ -8,10 +8,11 @@ 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);
@@ -29,24 +30,37 @@ export class MikroORMStorage extends Storage {
   }
 
   public async open(): Promise<void> {
-    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<void> {
-    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;
+      return `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
     }
     return this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME;
   }
 
   private getOptions(): Configuration<IDatabaseDriver<Connection>> | Options<IDatabaseDriver<Connection>> {
     return {
+      metadataProvider: TsMorphMetadataProvider,
       entities: [PerformanceRecord, PerformanceData],
-      dbName: this.dbName,
       type: this.storageType as MikroORMDBType,
       clientUrl: this.getClientUrl()
     };
@@ -55,7 +69,6 @@ export class MikroORMStorage extends Storage {
   private getClientUrl(): string {
     switch (this.storageType) {
       case StorageType.SQLITE:
-        return this.storageURI.pathname;
       case StorageType.MARIA_DB:
       case StorageType.MYSQL:
         return this.storageURI.toString();