chore: switch coding style to JS standard
[e-mobility-charging-stations-simulator.git] / src / performance / storage / MongoDBStorage.ts
CommitLineData
edd13439 1// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c27c3eee 2
66a7748d 3import { MongoClient } from 'mongodb'
8114d10e 4
66a7748d
JB
5import { Storage } from './Storage.js'
6import { BaseError } from '../../exception/index.js'
7import { type Statistics, StorageType } from '../../types/index.js'
8import { Constants } from '../../utils/index.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
e7aeea18
JB
18 this.dbName =
19 this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ??
66a7748d 20 Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
72f041bd
JB
21 }
22
66a7748d 23 public async storePerformanceStatistics (performanceStatistics: Statistics): Promise<void> {
2a370053 24 try {
66a7748d 25 this.checkDBConnection()
e7aeea18 26 await this.client
72092cfc 27 ?.db(this.dbName)
e7aeea18 28 .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE)
66a7748d 29 .replaceOne({ id: performanceStatistics.id }, performanceStatistics, { upsert: true })
2a370053 30 } catch (error) {
66a7748d 31 this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE)
2a370053 32 }
72f041bd
JB
33 }
34
66a7748d 35 public async open (): Promise<void> {
2a370053 36 try {
66a7748d
JB
37 if (!this.connected && this?.client != null) {
38 await this.client.connect()
39 this.connected = true
2a370053
JB
40 }
41 } catch (error) {
66a7748d 42 this.handleDBError(StorageType.MONGO_DB, error as Error)
2a370053
JB
43 }
44 }
72f041bd 45
66a7748d 46 public async close (): Promise<void> {
2a370053 47 try {
66a7748d
JB
48 if (this.connected && this?.client != null) {
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
JB
57 private checkDBConnection (): void {
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}