1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
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';
9 export class MongoDBStorage
extends Storage
{
10 private readonly client
: MongoClient
| null;
11 private connected
: boolean;
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
= this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '') ?? Constants
.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
;
20 public async storePerformanceStatistics(performanceStatistics
: Statistics
): Promise
<void> {
22 this.checkDBConnection();
23 await this.client
.db(this.dbName
).collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
).insertOne(performanceStatistics
);
25 this.handleDBError(StorageType
.MONGO_DB
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
);
29 public async open(): Promise
<void> {
31 if (!this.connected
&& this?.client
) {
32 await this.client
.connect();
33 this.connected
= true;
36 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
40 public async close(): Promise
<void> {
42 if (this.connected
&& this?.client
) {
43 await this.client
.close();
44 this.connected
= false;
47 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
51 private checkDBConnection() {
53 throw new Error(`${this.logPrefix} ${this.getDBNameFromStorageType(StorageType.MONGO_DB)} client initialization failed while trying to issue a request`);
55 if (!this.connected
) {
56 throw new Error(`${this.logPrefix} ${this.getDBNameFromStorageType(StorageType.MONGO_DB)} connection not opened while trying to issue a request`);