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