1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import Constants from
'../../utils/Constants';
4 import FileUtils from
'../../utils/FileUtils';
5 import Statistics from
'../../types/Statistics';
6 import { Storage
} from
'./Storage';
9 export class JSONFileStorage
extends Storage
{
10 private fd
: number | null = null;
12 constructor(storageURI
: string, logPrefix
: string) {
13 super(storageURI
, logPrefix
);
14 this.dbName
= this.storageURI
.pathname
;
17 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
18 this.checkPerformanceRecordsFile();
19 fs
.readFile(this.dbName
, 'utf-8', (error
, data
) => {
21 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
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
) => {
27 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, err
);
37 this.fd
= fs
.openSync(this.dbName
, 'a+');
40 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
44 public close(): void {
47 fs
.closeSync(this.fd
);
51 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
55 private checkPerformanceRecordsFile(): void {
57 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);