build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / performance / storage / Storage.ts
CommitLineData
a19b897d 1// Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
c27c3eee 2
66a7748d 3import { URL } from 'node:url'
c27c3eee 4
268a74bb
JB
5import {
6 DBName,
7 type EmptyObject,
8 type HandleErrorParams,
9 type Statistics,
66a7748d
JB
10 StorageType
11} from '../../types/index.js'
12import { logger, setDefaultErrorParams } from '../../utils/index.js'
72f041bd
JB
13
14export abstract class Storage {
66a7748d
JB
15 protected readonly storageUri: URL
16 protected readonly logPrefix: string
17 protected dbName!: string
a66bbcfe 18 private static readonly performanceStatistics = new Map<string, Statistics>()
72f041bd 19
66a7748d
JB
20 constructor (storageUri: string, logPrefix: string) {
21 this.storageUri = new URL(storageUri)
22 this.logPrefix = logPrefix
72f041bd
JB
23 }
24
a03b18c4 25 protected handleDBStorageError (
e7aeea18
JB
26 type: StorageType,
27 error: Error,
28 table?: string,
48847bc0
JB
29 params: HandleErrorParams<EmptyObject> = {
30 throwError: false,
31 consoleOut: false
32 }
e7aeea18 33 ): void {
30695dcf 34 params = setDefaultErrorParams(params, { throwError: false, consoleOut: false })
66a7748d 35 const inTableOrCollectionStr = table != null && ` in table or collection '${table}'`
e7aeea18 36 logger.error(
8f3d04b0
JB
37 `${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${
38 error.message
32de5a57 39 }'${inTableOrCollectionStr}:`,
66a7748d
JB
40 error
41 )
5199f9fd 42 if (params.throwError === true) {
66a7748d 43 throw error
e0a50bcd 44 }
c27c3eee
JB
45 }
46
66a7748d 47 protected getDBNameFromStorageType (type: StorageType): DBName | undefined {
c27c3eee 48 switch (type) {
4ccf551d
JB
49 case StorageType.SQLITE:
50 return DBName.SQLITE
c27c3eee 51 case StorageType.MARIA_DB:
66a7748d 52 return DBName.MARIA_DB
c27c3eee 53 case StorageType.MYSQL:
66a7748d 54 return DBName.MYSQL
4ccf551d
JB
55 case StorageType.MONGO_DB:
56 return DBName.MONGO_DB
c27c3eee 57 }
2a370053
JB
58 }
59
a66bbcfe
JB
60 public getPerformanceStatistics (): IterableIterator<Statistics> {
61 return Storage.performanceStatistics.values()
62 }
63
64 protected setPerformanceStatistics (performanceStatistics: Statistics): void {
65 Storage.performanceStatistics.set(performanceStatistics.id, performanceStatistics)
66 }
67
68 protected clearPerformanceStatistics (): void {
69 Storage.performanceStatistics.clear()
70 }
71
66a7748d
JB
72 public abstract open (): void | Promise<void>
73 public abstract close (): void | Promise<void>
74 public abstract storePerformanceStatistics (
75 performanceStatistics: Statistics
76 ): void | Promise<void>
72f041bd 77}