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