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
);
28 JSON
.stringify(performanceRecords
,
30 if (value
instanceof Map
) {
36 return value
as Statistics
;
42 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
as NodeJS
.ErrnoException
);
46 .catch(() => { /* This is intentional */ });
52 this.fd
= fs
.openSync(this.dbName
, 'a+');
55 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
as NodeJS
.ErrnoException
);
59 public close(): void {
62 fs
.closeSync(this.fd
);
66 FileUtils
.handleFileException(this.logPrefix
, Constants
.PERFORMANCE_RECORDS_FILETYPE
, this.dbName
, error
as NodeJS
.ErrnoException
);
70 private checkPerformanceRecordsFile(): void {
72 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);