| 1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import Constants from '../../utils/Constants'; |
| 4 | import FileUtils from '../../utils/FileUtils'; |
| 5 | import Statistics from '../../types/Statistics'; |
| 6 | import { Storage } from './Storage'; |
| 7 | import fs from 'fs'; |
| 8 | |
| 9 | export class JSONFileStorage extends Storage { |
| 10 | private fd: number | null = null; |
| 11 | |
| 12 | constructor(storageURI: string, logPrefix: string) { |
| 13 | super(storageURI, logPrefix); |
| 14 | this.dbName = this.storageURI.pathname; |
| 15 | } |
| 16 | |
| 17 | public storePerformanceStatistics(performanceStatistics: Statistics): void { |
| 18 | this.checkPerformanceRecordsFile(); |
| 19 | fs.readFile(this.dbName, 'utf-8', (error, data) => { |
| 20 | if (error) { |
| 21 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
| 22 | } else { |
| 23 | const performanceRecords: Statistics[] = data ? JSON.parse(data) as Statistics[] : []; |
| 24 | performanceRecords.push(performanceStatistics); |
| 25 | fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => { |
| 26 | if (err) { |
| 27 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, err); |
| 28 | } |
| 29 | }); |
| 30 | } |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | public open(): void { |
| 35 | try { |
| 36 | if (!this?.fd) { |
| 37 | this.fd = fs.openSync(this.dbName, 'a+'); |
| 38 | } |
| 39 | } catch (error) { |
| 40 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public close(): void { |
| 45 | try { |
| 46 | if (this?.fd) { |
| 47 | fs.closeSync(this.fd); |
| 48 | this.fd = null; |
| 49 | } |
| 50 | } catch (error) { |
| 51 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | private checkPerformanceRecordsFile(): void { |
| 56 | if (!this?.fd) { |
| 57 | throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`); |
| 58 | } |
| 59 | } |
| 60 | } |