build: bump volta node version
[e-mobility-charging-stations-simulator.git] / src / performance / storage / Storage.ts
1 // Copyright Jerome Benoit. 2021-2024. 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 } 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 private static readonly performanceStatistics = new Map<string, Statistics>()
19
20 constructor (storageUri: string, logPrefix: string) {
21 this.storageUri = new URL(storageUri)
22 this.logPrefix = logPrefix
23 }
24
25 protected handleDBStorageError (
26 type: StorageType,
27 error: Error,
28 table?: string,
29 params: HandleErrorParams<EmptyObject> = {
30 throwError: false,
31 consoleOut: false
32 }
33 ): void {
34 params = {
35 ...{
36 throwError: false,
37 consoleOut: false
38 },
39 ...params
40 }
41 const inTableOrCollectionStr = table != null && ` in table or collection '${table}'`
42 logger.error(
43 `${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${
44 error.message
45 }'${inTableOrCollectionStr}:`,
46 error
47 )
48 if (params.throwError === true) {
49 throw error
50 }
51 }
52
53 protected getDBNameFromStorageType (type: StorageType): DBName | undefined {
54 switch (type) {
55 case StorageType.SQLITE:
56 return DBName.SQLITE
57 case StorageType.MARIA_DB:
58 return DBName.MARIA_DB
59 case StorageType.MYSQL:
60 return DBName.MYSQL
61 case StorageType.MONGO_DB:
62 return DBName.MONGO_DB
63 }
64 }
65
66 public getPerformanceStatistics (): IterableIterator<Statistics> {
67 return Storage.performanceStatistics.values()
68 }
69
70 protected setPerformanceStatistics (performanceStatistics: Statistics): void {
71 Storage.performanceStatistics.set(performanceStatistics.id, performanceStatistics)
72 }
73
74 protected clearPerformanceStatistics (): void {
75 Storage.performanceStatistics.clear()
76 }
77
78 public abstract open (): void | Promise<void>
79 public abstract close (): void | Promise<void>
80 public abstract storePerformanceStatistics (
81 performanceStatistics: Statistics
82 ): void | Promise<void>
83 }