chore: switch coding style to JS standard
[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/index.js'
12 import { logger, setDefaultErrorParams } from '../../utils/index.js'
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, consoleOut: false }
29 ): void {
30 setDefaultErrorParams(params, { throwError: false, consoleOut: false })
31 const inTableOrCollectionStr = table != null && ` 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 === true) {
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 }