56689a560b2c0d3cd61559c262cdb3f5931327ea
[e-mobility-charging-stations-simulator.git] / src / utils / performance-storage / MongoDBStorage.ts
1 import Constants from '../Constants';
2 import { DBType } from '../../types/Storage';
3 import { MongoClient } from 'mongodb';
4 import Statistics from '../../types/Statistics';
5 import { Storage } from './Storage';
6
7 export class MongoDBStorage extends Storage {
8 private client: MongoClient;
9 private connected: boolean;
10
11 constructor(storageURI: string, logPrefix: string) {
12 super(storageURI, logPrefix);
13 this.client = new MongoClient(this.storageURI.toString());
14 this.connected = false;
15 this.dbName = this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME;
16 }
17
18 public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> {
19 try {
20 this.checkDBConnection();
21 await this.client.db(this.dbName).collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE).insertOne(performanceStatistics);
22 } catch (error) {
23 this.handleDBError(DBType.MONGO_DB, error, Constants.PERFORMANCE_RECORDS_TABLE);
24 }
25 }
26
27 public async open(): Promise<void> {
28 try {
29 if (!this.connected) {
30 await this.client.connect();
31 this.connected = true;
32 }
33 } catch (error) {
34 this.handleDBError(DBType.MONGO_DB, error);
35 }
36 }
37
38 public async close(): Promise<void> {
39 try {
40 if (this.connected) {
41 await this.client.close();
42 this.connected = false;
43 }
44 } catch (error) {
45 this.handleDBError(DBType.MONGO_DB, error);
46 }
47 }
48
49 private checkDBConnection() {
50 if (!this.connected) {
51 throw new Error(`${this.logPrefix} ${DBType.MONGO_DB} connection not opened while trying to issue a request`);
52 }
53 }
54 }