feat: add performance statistics to UI protocol
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MongoDBStorage.ts
1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
2
3 import { MongoClient } from 'mongodb'
4
5 import { Storage } from './Storage.js'
6 import { BaseError } from '../../exception/index.js'
7 import { type Statistics, StorageType } from '../../types/index.js'
8 import { Constants } from '../../utils/index.js'
9
10 export class MongoDBStorage extends Storage {
11 private readonly client?: MongoClient
12 private connected: boolean
13
14 constructor (storageUri: string, logPrefix: string) {
15 super(storageUri, logPrefix)
16 this.client = new MongoClient(this.storageUri.toString())
17 this.connected = false
18 this.dbName = this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '')
19 }
20
21 public async storePerformanceStatistics (performanceStatistics: Statistics): Promise<void> {
22 try {
23 this.setPerformanceStatistics(performanceStatistics)
24 this.checkDBConnection()
25 await this.client
26 ?.db(this.dbName)
27 .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE)
28 .replaceOne({ id: performanceStatistics.id }, performanceStatistics, { upsert: true })
29 } catch (error) {
30 this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE)
31 }
32 }
33
34 public async open (): Promise<void> {
35 try {
36 if (!this.connected && this.client != null) {
37 await this.client.connect()
38 this.connected = true
39 }
40 } catch (error) {
41 this.handleDBError(StorageType.MONGO_DB, error as Error)
42 }
43 }
44
45 public async close (): Promise<void> {
46 this.clearPerformanceStatistics()
47 try {
48 if (this.connected && this.client != null) {
49 await this.client.close()
50 this.connected = false
51 }
52 } catch (error) {
53 this.handleDBError(StorageType.MONGO_DB, error as Error)
54 }
55 }
56
57 private checkDBConnection (): void {
58 if (this.client == null) {
59 throw new BaseError(
60 `${this.logPrefix} ${this.getDBNameFromStorageType(
61 StorageType.MONGO_DB
62 )} client initialization failed while trying to issue a request`
63 )
64 }
65 if (!this.connected) {
66 throw new BaseError(
67 `${this.logPrefix} ${this.getDBNameFromStorageType(
68 StorageType.MONGO_DB
69 )} connection not opened while trying to issue a request`
70 )
71 }
72 }
73 }