refactor: switch eslint configuration to strict type checking
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MongoDBStorage.ts
1 // Copyright Jerome Benoit. 2021-2023. 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.checkDBConnection()
24 await this.client
25 ?.db(this.dbName)
26 .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE)
27 .replaceOne({ id: performanceStatistics.id }, performanceStatistics, { upsert: true })
28 } catch (error) {
29 this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE)
30 }
31 }
32
33 public async open (): Promise<void> {
34 try {
35 if (!this.connected && this.client != null) {
36 await this.client.connect()
37 this.connected = true
38 }
39 } catch (error) {
40 this.handleDBError(StorageType.MONGO_DB, error as Error)
41 }
42 }
43
44 public async close (): Promise<void> {
45 try {
46 if (this.connected && this.client != null) {
47 await this.client.close()
48 this.connected = false
49 }
50 } catch (error) {
51 this.handleDBError(StorageType.MONGO_DB, error as Error)
52 }
53 }
54
55 private checkDBConnection (): void {
56 if (this.client == null) {
57 throw new BaseError(
58 `${this.logPrefix} ${this.getDBNameFromStorageType(
59 StorageType.MONGO_DB
60 )} client initialization failed while trying to issue a request`
61 )
62 }
63 if (!this.connected) {
64 throw new BaseError(
65 `${this.logPrefix} ${this.getDBNameFromStorageType(
66 StorageType.MONGO_DB
67 )} connection not opened while trying to issue a request`
68 )
69 }
70 }
71 }