fix(ocpp-server): silence linter
[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.handleDBStorageError(
33 StorageType.MONGO_DB,
34 error as Error,
35 Constants.PERFORMANCE_RECORDS_TABLE
36 )
37 }
38 }
39
40 public async open (): Promise<void> {
41 try {
42 if (!this.connected && this.client != null) {
43 await this.client.connect()
44 this.connected = true
45 }
46 } catch (error) {
47 this.handleDBStorageError(StorageType.MONGO_DB, error as Error)
48 }
49 }
50
51 public async close (): Promise<void> {
52 this.clearPerformanceStatistics()
53 try {
54 if (this.connected && this.client != null) {
55 await this.client.close()
56 this.connected = false
57 }
58 } catch (error) {
59 this.handleDBStorageError(StorageType.MONGO_DB, error as Error)
60 }
61 }
62
63 private checkDBConnection (): void {
64 if (this.client == null) {
65 throw new BaseError(
66 `${this.logPrefix} ${this.getDBNameFromStorageType(
67 StorageType.MONGO_DB
68 )} client initialization failed while trying to issue a request`
69 )
70 }
71 if (!this.connected) {
72 throw new BaseError(
73 `${this.logPrefix} ${this.getDBNameFromStorageType(
74 StorageType.MONGO_DB
75 )} connection not opened while trying to issue a request`
76 )
77 }
78 }
79 }