| 1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import { MongoClient } from 'mongodb'; |
| 4 | |
| 5 | import type Statistics from '../../types/Statistics'; |
| 6 | import { StorageType } from '../../types/Storage'; |
| 7 | import Constants from '../../utils/Constants'; |
| 8 | import { Storage } from './Storage'; |
| 9 | |
| 10 | export class MongoDBStorage extends Storage { |
| 11 | private readonly client: MongoClient | null; |
| 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 = |
| 19 | this.storageUri.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? |
| 20 | Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; |
| 21 | } |
| 22 | |
| 23 | public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> { |
| 24 | try { |
| 25 | this.checkDBConnection(); |
| 26 | await this.client |
| 27 | .db(this.dbName) |
| 28 | .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE) |
| 29 | .insertOne(performanceStatistics); |
| 30 | } catch (error) { |
| 31 | this.handleDBError(StorageType.MONGO_DB, error as Error, Constants.PERFORMANCE_RECORDS_TABLE); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public async open(): Promise<void> { |
| 36 | try { |
| 37 | if (!this.connected && this?.client) { |
| 38 | await this.client.connect(); |
| 39 | this.connected = true; |
| 40 | } |
| 41 | } catch (error) { |
| 42 | this.handleDBError(StorageType.MONGO_DB, error as Error); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public async close(): Promise<void> { |
| 47 | try { |
| 48 | if (this.connected && this?.client) { |
| 49 | await this.client.close(); |
| 50 | this.connected = false; |
| 51 | } |
| 52 | } catch (error) { |
| 53 | this.handleDBError(StorageType.MONGO_DB, error as Error); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private checkDBConnection() { |
| 58 | if (!this?.client) { |
| 59 | throw new Error( |
| 60 | `${this.logPrefix} ${this.getDBNameFromStorageType( |
| 61 | StorageType.MONGO_DB |
| 62 | )} client initialization failed while trying to issue a request` |
| 63 | ); |
| 64 | } |
| 65 | if (!this.connected) { |
| 66 | throw new Error( |
| 67 | `${this.logPrefix} ${this.getDBNameFromStorageType( |
| 68 | StorageType.MONGO_DB |
| 69 | )} connection not opened while trying to issue a request` |
| 70 | ); |
| 71 | } |
| 72 | } |
| 73 | } |