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