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