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