build(deps-dev): apply updates
[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 { BaseError } from '../../exception/index.js'
6 import { type Statistics, StorageType } from '../../types/index.js'
7 import { Constants } from '../../utils/index.js'
8 import { Storage } from './Storage.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, {
29 upsert: true
30 })
31 } catch (error) {
32 this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE)
33 }
34 }
35
36 public async open (): Promise<void> {
37 try {
38 if (!this.connected && this.client != null) {
39 await this.client.connect()
40 this.connected = true
41 }
42 } catch (error) {
43 this.handleDBError(StorageType.MONGO_DB, error as Error)
44 }
45 }
46
47 public async close (): Promise<void> {
48 this.clearPerformanceStatistics()
49 try {
50 if (this.connected && this.client != null) {
51 await this.client.close()
52 this.connected = false
53 }
54 } catch (error) {
55 this.handleDBError(StorageType.MONGO_DB, error as Error)
56 }
57 }
58
59 private checkDBConnection (): void {
60 if (this.client == null) {
61 throw new BaseError(
62 `${this.logPrefix} ${this.getDBNameFromStorageType(
63 StorageType.MONGO_DB
64 )} client initialization failed while trying to issue a request`
65 )
66 }
67 if (!this.connected) {
68 throw new BaseError(
69 `${this.logPrefix} ${this.getDBNameFromStorageType(
70 StorageType.MONGO_DB
71 )} connection not opened while trying to issue a request`
72 )
73 }
74 }
75 }