Version 1.1.50
[e-mobility-charging-stations-simulator.git] / src / performance / storage / Storage.ts
1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { DBName, StorageType } from '../../types/Storage';
4
5 import { HandleErrorParams } from '../../types/Error';
6 import Statistics from '../../types/Statistics';
7 import { URL } from 'url';
8 import Utils from '../../utils/Utils';
9 import logger from '../../utils/Logger';
10
11 export abstract class Storage {
12 protected readonly storageUri: URL;
13 protected readonly logPrefix: string;
14 protected dbName: string;
15
16 constructor(storageUri: string, logPrefix: string) {
17 this.storageUri = new URL(storageUri);
18 this.logPrefix = logPrefix;
19 }
20
21 protected handleDBError(type: StorageType, error: Error, table?: string, params: HandleErrorParams = { throwError: false }): void {
22 logger.error(`${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${error.message}'${(!Utils.isNullOrUndefined(table) || !table) && ` in table or collection '${table}'`}: %j`, error);
23 if (params?.throwError) {
24 throw error;
25 }
26 }
27
28 protected getDBNameFromStorageType(type: StorageType): DBName {
29 switch (type) {
30 case StorageType.MARIA_DB:
31 return DBName.MARIA_DB;
32 case StorageType.MONGO_DB:
33 return DBName.MONGO_DB;
34 case StorageType.MYSQL:
35 return DBName.MYSQL;
36 case StorageType.SQLITE:
37 return DBName.SQLITE;
38 }
39 }
40
41 public abstract open(): void | Promise<void>;
42 public abstract close(): void | Promise<void>;
43 public abstract storePerformanceStatistics(performanceStatistics: Statistics): void | Promise<void>;
44 }