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