1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { MongoClient
} from
'mongodb'
5 import { BaseError
} from
'../../exception/index.js'
6 import { type Statistics
, StorageType
} from
'../../types/index.js'
7 import { Constants
} from
'../../utils/index.js'
8 import { Storage
} from
'./Storage.js'
10 export class MongoDBStorage
extends Storage
{
11 private readonly client
?: MongoClient
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
18 this.dbName
= this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '')
21 public async storePerformanceStatistics (performanceStatistics
: Statistics
): Promise
<void> {
23 this.setPerformanceStatistics(performanceStatistics
)
24 this.checkDBConnection()
27 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
28 .replaceOne({ id
: performanceStatistics
.id
}, performanceStatistics
, {
32 this.handleDBStorageError(
35 Constants
.PERFORMANCE_RECORDS_TABLE
40 public async open (): Promise
<void> {
42 if (!this.connected
&& this.client
!= null) {
43 await this.client
.connect()
47 this.handleDBStorageError(StorageType
.MONGO_DB
, error
as Error)
51 public async close (): Promise
<void> {
52 this.clearPerformanceStatistics()
54 if (this.connected
&& this.client
!= null) {
55 await this.client
.close()
56 this.connected
= false
59 this.handleDBStorageError(StorageType
.MONGO_DB
, error
as Error)
63 private checkDBConnection (): void {
64 if (this.client
== null) {
66 `${this.logPrefix} ${this.getDBNameFromStorageType(
68 )} client initialization failed while trying to issue a request`
71 if (!this.connected
) {
73 `${this.logPrefix} ${this.getDBNameFromStorageType(
75 )} connection not opened while trying to issue a request`