| 1 | // Copyright Jerome Benoit. 2021-2024. All Rights Reserved. |
| 2 | |
| 3 | import { MongoClient } from 'mongodb' |
| 4 | |
| 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' |
| 9 | |
| 10 | export class MongoDBStorage extends Storage { |
| 11 | private readonly client?: MongoClient |
| 12 | private connected: boolean |
| 13 | |
| 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, '') |
| 19 | } |
| 20 | |
| 21 | private checkDBConnection (): void { |
| 22 | if (this.client == null) { |
| 23 | throw new BaseError( |
| 24 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 25 | `${this.logPrefix} ${this.getDBNameFromStorageType( |
| 26 | StorageType.MONGO_DB |
| 27 | )} client initialization failed while trying to issue a request` |
| 28 | ) |
| 29 | } |
| 30 | if (!this.connected) { |
| 31 | throw new BaseError( |
| 32 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 33 | `${this.logPrefix} ${this.getDBNameFromStorageType( |
| 34 | StorageType.MONGO_DB |
| 35 | )} connection not opened while trying to issue a request` |
| 36 | ) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | public async close (): Promise<void> { |
| 41 | this.clearPerformanceStatistics() |
| 42 | try { |
| 43 | if (this.connected && this.client != null) { |
| 44 | await this.client.close() |
| 45 | this.connected = false |
| 46 | } |
| 47 | } catch (error) { |
| 48 | this.handleDBStorageError(StorageType.MONGO_DB, error as Error) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public async open (): Promise<void> { |
| 53 | try { |
| 54 | if (!this.connected && this.client != null) { |
| 55 | await this.client.connect() |
| 56 | this.connected = true |
| 57 | } |
| 58 | } catch (error) { |
| 59 | this.handleDBStorageError(StorageType.MONGO_DB, error as Error) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | public async storePerformanceStatistics (performanceStatistics: Statistics): Promise<void> { |
| 64 | try { |
| 65 | this.setPerformanceStatistics(performanceStatistics) |
| 66 | this.checkDBConnection() |
| 67 | await this.client |
| 68 | ?.db(this.dbName) |
| 69 | .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE) |
| 70 | .replaceOne({ id: performanceStatistics.id }, performanceStatistics, { |
| 71 | upsert: true, |
| 72 | }) |
| 73 | } catch (error) { |
| 74 | this.handleDBStorageError( |
| 75 | StorageType.MONGO_DB, |
| 76 | error as Error, |
| 77 | Constants.PERFORMANCE_RECORDS_TABLE |
| 78 | ) |
| 79 | } |
| 80 | } |
| 81 | } |