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';
8 import lockfile from
'proper-lockfile';
10 export class JSONFileStorage
extends Storage
{
11 private fd
: number | null = null;
13 constructor(storageURI
: string, logPrefix
: string) {
14 super(storageURI
, logPrefix
);
15 this.dbName
= this.storageURI
.pathname
;
18 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
19 this.checkPerformanceRecordsFile();
20 lockfile
.lock(this.dbName
, { stale
: 5000, retries
: 3 })
21 .then(async (release
) => {
23 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
24 const performanceRecords
: Statistics
[] = fileData
? JSON
.parse(fileData
) as Statistics
[] : [];
25 performanceRecords
.push(performanceStatistics
);
26 fs
.writeFileSync(this.dbName
, JSON
.stringify(performanceRecords
, null, 2), 'utf8');
28 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
38 this.fd
= fs
.openSync(this.dbName
, 'a+');
41 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
45 public close(): void {
48 fs
.closeSync(this.fd
);
52 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
);
56 private checkPerformanceRecordsFile(): void {
58 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);