Commit | Line | Data |
---|---|---|
a6b3c6c3 JB |
1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
3 | import { Configuration, Connection, IDatabaseDriver, MikroORM, Options } from '@mikro-orm/core'; | |
4 | import { MikroORMDBType, StorageType } from '../../types/Storage'; | |
5 | ||
6 | import Constants from '../../utils/Constants'; | |
7 | import { PerformanceData } from '../../types/orm/entities/PerformanceData'; | |
8 | import { PerformanceRecord } from '../../types/orm/entities/PerformanceRecord'; | |
9 | import Statistics from '../../types/Statistics'; | |
10 | import { Storage } from './Storage'; | |
11 | ||
12 | export class MikroORMStorage extends Storage { | |
13 | private storageType: StorageType; | |
14 | private orm: MikroORM; | |
15 | ||
16 | constructor(storageURI: string, logPrefix: string, storageType: StorageType) { | |
17 | super(storageURI, logPrefix); | |
18 | this.storageType = storageType; | |
d5603918 | 19 | this.dbName = this.getDBName(); |
a6b3c6c3 JB |
20 | } |
21 | ||
22 | public async storePerformanceStatistics(performanceStatistics: Statistics): Promise<void> { | |
23 | try { | |
24 | const performanceRecord = new PerformanceRecord(); | |
25 | await this.orm.em.persistAndFlush(performanceRecord); | |
26 | } catch (error) { | |
27 | this.handleDBError(this.storageType, error, Constants.PERFORMANCE_RECORDS_TABLE); | |
28 | } | |
29 | } | |
30 | ||
31 | public async open(): Promise<void> { | |
32 | this.orm = await MikroORM.init(this.getOptions(), true); | |
33 | } | |
34 | ||
35 | public async close(): Promise<void> { | |
36 | await this.orm.close(); | |
37 | } | |
38 | ||
d5603918 JB |
39 | private getDBName(): string { |
40 | if (this.storageType === StorageType.SQLITE) { | |
41 | return Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; | |
42 | } | |
43 | return this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '') ?? Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME; | |
44 | } | |
45 | ||
a6b3c6c3 JB |
46 | private getOptions(): Configuration<IDatabaseDriver<Connection>> | Options<IDatabaseDriver<Connection>> { |
47 | return { | |
48 | entities: [PerformanceRecord, PerformanceData], | |
49 | dbName: this.dbName, | |
50 | type: this.storageType as MikroORMDBType, | |
d5603918 | 51 | clientUrl: this.getClientUrl() |
a6b3c6c3 JB |
52 | }; |
53 | } | |
d5603918 JB |
54 | |
55 | private getClientUrl(): string { | |
56 | switch (this.storageType) { | |
57 | case StorageType.SQLITE: | |
58 | return this.storageURI.pathname; | |
59 | case StorageType.MARIA_DB: | |
60 | case StorageType.MYSQL: | |
61 | return this.storageURI.toString(); | |
62 | } | |
63 | } | |
a6b3c6c3 JB |
64 | } |
65 |