1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
5 import lockfile from
'proper-lockfile';
7 import { Storage
} from
'./Storage';
8 import { FileType
} from
'../../types/FileType';
9 import type { Statistics
} from
'../../types/Statistics';
10 import FileUtils from
'../../utils/FileUtils';
11 import Utils from
'../../utils/Utils';
13 export class JsonFileStorage
extends Storage
{
14 private fd
: number | null = null;
16 constructor(storageUri
: string, logPrefix
: string) {
17 super(storageUri
, logPrefix
);
18 this.dbName
= this.storageUri
.pathname
;
21 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
22 this.checkPerformanceRecordsFile();
24 .lock(this.dbName
, { stale
: 5000, retries
: 3 })
25 .then(async release
=> {
27 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
28 const performanceRecords
: Statistics
[] = fileData
29 ? (JSON
.parse(fileData
) as Statistics
[])
31 performanceRecords
.push(performanceStatistics
);
34 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
38 FileUtils
.handleFileException(
40 FileType
.PerformanceRecords
,
42 error
as NodeJS
.ErrnoException
48 /* This is intentional */
55 this.fd
= fs
.openSync(this.dbName
, 'a+');
58 FileUtils
.handleFileException(
60 FileType
.PerformanceRecords
,
62 error
as NodeJS
.ErrnoException
67 public close(): void {
70 fs
.closeSync(this.fd
);
74 FileUtils
.handleFileException(
76 FileType
.PerformanceRecords
,
78 error
as NodeJS
.ErrnoException
83 private checkPerformanceRecordsFile(): void {
86 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`