Commit | Line | Data |
---|---|---|
c27c3eee JB |
1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
a6b3c6c3 | 3 | import Constants from '../../utils/Constants'; |
2a370053 | 4 | import { MongoClient } from 'mongodb'; |
72f041bd JB |
5 | import Statistics from '../../types/Statistics'; |
6 | import { Storage } from './Storage'; | |
c27c3eee | 7 | import { StorageType } from '../../types/Storage'; |
72f041bd JB |
8 | |
9 | export class MongoDBStorage extends Storage { | |
a6ceb16a | 10 | private client: MongoClient | null; |
2a370053 JB |
11 | private connected: boolean; |
12 | ||
72f041bd JB |
13 | constructor(storageURI: string, logPrefix: string) { |
14 | super(storageURI, logPrefix); | |
2a370053 JB |
15 | this.client = new MongoClient(this.storageURI.toString()); |
16 | this.connected = false; | |
17 | this.dbName = this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; | |
72f041bd JB |
18 | } |
19 | ||
2a370053 JB |
20 | public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> { |
21 | try { | |
22 | this.checkDBConnection(); | |
23 | await this.client.db(this.dbName).collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE).insertOne(performanceStatistics); | |
24 | } catch (error) { | |
c27c3eee | 25 | this.handleDBError(StorageType.MONGO_DB, error, Constants.PERFORMANCE_RECORDS_TABLE); |
2a370053 | 26 | } |
72f041bd JB |
27 | } |
28 | ||
2a370053 JB |
29 | public async open(): Promise<void> { |
30 | try { | |
a6ceb16a | 31 | if (!this.connected && this?.client) { |
2a370053 JB |
32 | await this.client.connect(); |
33 | this.connected = true; | |
34 | } | |
35 | } catch (error) { | |
c27c3eee | 36 | this.handleDBError(StorageType.MONGO_DB, error); |
2a370053 JB |
37 | } |
38 | } | |
72f041bd | 39 | |
2a370053 JB |
40 | public async close(): Promise<void> { |
41 | try { | |
a6ceb16a | 42 | if (this.connected && this?.client) { |
2a370053 JB |
43 | await this.client.close(); |
44 | this.connected = false; | |
45 | } | |
46 | } catch (error) { | |
c27c3eee | 47 | this.handleDBError(StorageType.MONGO_DB, error); |
2a370053 JB |
48 | } |
49 | } | |
50 | ||
51 | private checkDBConnection() { | |
a6ceb16a JB |
52 | if (!this?.client) { |
53 | throw new Error(`${this.logPrefix} ${this.getDBNameFromStorageType(StorageType.MONGO_DB)} client initialization failed while trying to issue a request`); | |
54 | } | |
2a370053 | 55 | if (!this.connected) { |
a6b3c6c3 | 56 | throw new Error(`${this.logPrefix} ${this.getDBNameFromStorageType(StorageType.MONGO_DB)} connection not opened while trying to issue a request`); |
2a370053 JB |
57 | } |
58 | } | |
72f041bd | 59 | } |