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
, { upsert
: true })
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
!= null) {
37 await this.client
.connect()
41 this.handleDBError(StorageType
.MONGO_DB
, error
as Error)
45 public async close (): Promise
<void> {
46 this.clearPerformanceStatistics()
48 if (this.connected
&& this.client
!= null) {
49 await this.client
.close()
50 this.connected
= false
53 this.handleDBError(StorageType
.MONGO_DB
, error
as Error)
57 private checkDBConnection (): void {
58 if (this.client
== null) {
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`