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