1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { MongoClient
} from
'mongodb';
5 import { type Statistics
, StorageType
} from
'../../types';
6 import { Constants
} from
'../../utils';
7 import { Storage
} from
'../internal';
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;
18 this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '') ??
19 Constants
.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
;
22 public async storePerformanceStatistics(performanceStatistics
: Statistics
): Promise
<void> {
24 this.checkDBConnection();
27 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
28 .insertOne(performanceStatistics
);
30 this.handleDBError(StorageType
.MONGO_DB
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
);
34 public async open(): Promise
<void> {
36 if (!this.connected
&& this?.client
) {
37 await this.client
.connect();
38 this.connected
= true;
41 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
45 public async close(): Promise
<void> {
47 if (this.connected
&& this?.client
) {
48 await this.client
.close();
49 this.connected
= false;
52 this.handleDBError(StorageType
.MONGO_DB
, error
as Error);
56 private checkDBConnection() {
59 `${this.logPrefix} ${this.getDBNameFromStorageType(
61 )} client initialization failed while trying to issue a request`
64 if (!this.connected
) {
66 `${this.logPrefix} ${this.getDBNameFromStorageType(
68 )} connection not opened while trying to issue a request`