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 private checkDBConnection (): void {
22 if (this.client
== null) {
24 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
25 `${this.logPrefix} ${this.getDBNameFromStorageType(
27 )} client initialization failed while trying to issue a request`
30 if (!this.connected
) {
32 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
33 `${this.logPrefix} ${this.getDBNameFromStorageType(
35 )} connection not opened while trying to issue a request`
40 public async close (): Promise
<void> {
41 this.clearPerformanceStatistics()
43 if (this.connected
&& this.client
!= null) {
44 await this.client
.close()
45 this.connected
= false
48 this.handleDBStorageError(StorageType
.MONGO_DB
, error
as Error)
52 public async open (): Promise
<void> {
54 if (!this.connected
&& this.client
!= null) {
55 await this.client
.connect()
59 this.handleDBStorageError(StorageType
.MONGO_DB
, error
as Error)
63 public async storePerformanceStatistics (performanceStatistics
: Statistics
): Promise
<void> {
65 this.setPerformanceStatistics(performanceStatistics
)
66 this.checkDBConnection()
69 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
70 .replaceOne({ id
: performanceStatistics
.id
}, performanceStatistics
, {
74 this.handleDBStorageError(
77 Constants
.PERFORMANCE_RECORDS_TABLE