1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { MongoClient
} from
'mongodb'
5 import { Storage
} from
'./Storage.js'
6 import { BaseError
} from
'../../exception/index.js'
7 import { type Statistics
, StorageType
} from
'../../types/index.js'
8 import { Constants
} from
'../../utils/index.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.checkDBConnection()
26 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
27 .replaceOne({ id
: performanceStatistics
.id
}, performanceStatistics
, { upsert
: true })
29 this.handleDBError(StorageType
.MONGO_DB
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
)
33 public async open (): Promise
<void> {
35 if (!this.connected
&& this.client
!= null) {
36 await this.client
.connect()
40 this.handleDBError(StorageType
.MONGO_DB
, error
as Error)
44 public async close (): Promise
<void> {
46 if (this.connected
&& this.client
!= null) {
47 await this.client
.close()
48 this.connected
= false
51 this.handleDBError(StorageType
.MONGO_DB
, error
as Error)
55 private checkDBConnection (): void {
56 if (this.client
== null) {
58 `${this.logPrefix} ${this.getDBNameFromStorageType(
60 )} client initialization failed while trying to issue a request`
63 if (!this.connected
) {
65 `${this.logPrefix} ${this.getDBNameFromStorageType(
67 )} connection not opened while trying to issue a request`