1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { MongoClient
} from
'mongodb';
5 import Statistics from
'../../types/Statistics';
6 import { StorageType
} from
'../../types/Storage';
7 import Constants from
'../../utils/Constants';
8 import { Storage
} from
'./Storage';
10 export class MongoDBStorage
extends Storage
{
11 private readonly client
: MongoClient
| null;
12 private connected
: boolean;
14 constructor(storageUri
: string, logPrefix
: string) {
15 super(storageUri
, logPrefix
);
16 this.client
= new MongoClient(this.storageUri
.toString());
17 this.connected
= false;
19 this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '') ??
20 Constants
.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
;
23 public async storePerformanceStatistics(performanceStatistics
: Statistics
): Promise
<void> {
25 this.checkDBConnection();
28 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
29 .insertOne(performanceStatistics
);
31 this.handleDBError(StorageType
.MONGO_DB
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
);
35 public async open(): Promise
<void> {
37 if (!this.connected
&& this?.client
) {
38 await this.client
.connect();
39 this.connected
= true;
42 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
46 public async close(): Promise
<void> {
48 if (this.connected
&& this?.client
) {
49 await this.client
.close();
50 this.connected
= false;
53 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
57 private checkDBConnection() {
60 `${this.logPrefix} ${this.getDBNameFromStorageType(
62 )} client initialization failed while trying to issue a request`
65 if (!this.connected
) {
67 `${this.logPrefix} ${this.getDBNameFromStorageType(
69 )} connection not opened while trying to issue a request`