X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2Fperformance-storage%2FJSONFileStorage.ts;h=ed1b122c1ee532bb7ef907b0d18064ebd50ab7e5;hb=2a370053f45f2d58e90ab7b292294c521a262ca1;hp=af709d9105440e594894388a9bd1b77997cde7db;hpb=72f041bd50fc25ca5d233565cbc0ea836220ec0f;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/performance-storage/JSONFileStorage.ts b/src/utils/performance-storage/JSONFileStorage.ts index af709d91..ed1b122c 100644 --- a/src/utils/performance-storage/JSONFileStorage.ts +++ b/src/utils/performance-storage/JSONFileStorage.ts @@ -1,3 +1,4 @@ +import Constants from '../Constants'; import FileUtils from '../FileUtils'; import Statistics from '../../types/Statistics'; import { Storage } from './Storage'; @@ -5,16 +6,52 @@ import fs from 'fs'; import path from 'path'; export class JSONFileStorage extends Storage { + private fd: number | null = null; + constructor(storageURI: string, logPrefix: string) { super(storageURI, logPrefix); + this.dbName = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '')); } public storePerformanceStatistics(performanceStatistics: Statistics): void { - const performanceJSONFilePath = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/^\/|\/$/g, '')); - fs.appendFile(performanceJSONFilePath, JSON.stringify(performanceStatistics, null, 2), 'utf8', (err) => { - if (err) { - FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, err); + this.checkPerformanceRecordsFile(); + fs.readFile(this.dbName, 'utf-8', (error, data) => { + if (error) { + FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); + } else { + const performanceRecords: Statistics[] = data ? JSON.parse(data) as Statistics[] : []; + performanceRecords.push(performanceStatistics); + fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => { + if (err) { + FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, err); + } + }); } }); } + + public open(): void { + try { + this.fd = fs.openSync(this.dbName, 'a+'); + } catch (error) { + FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); + } + } + + public close(): void { + try { + if (this.fd) { + fs.closeSync(this.fd); + this.fd = null; + } + } catch (error) { + FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); + } + } + + private checkPerformanceRecordsFile(): void { + if (!this.fd) { + throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`); + } + } }