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
19 this.storageUri
.pathname
.replace(/(?:^\
/)|(?:\
/$
)/g
, '') ??
20 Constants
.DEFAULT_PERFORMANCE_RECORDS_DB_NAME
23 public async storePerformanceStatistics (performanceStatistics
: Statistics
): Promise
<void> {
25 this.checkDBConnection()
28 .collection
<Statistics
>(Constants
.PERFORMANCE_RECORDS_TABLE
)
29 .replaceOne({ id
: performanceStatistics
.id
}, performanceStatistics
, { upsert
: true })
31 this.handleDBError(StorageType
.MONGO_DB
, error
as Error, Constants
.PERFORMANCE_RECORDS_TABLE
)
35 public async open (): Promise
<void> {
37 if (!this.connected
&& this?.client
!= null) {
38 await this.client
.connect()
42 this.handleDBError(StorageType
.MONGO_DB
, error
as Error)
46 public async close (): Promise
<void> {
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`