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