1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
5 import lockfile from
'proper-lockfile';
7 import { FileType
} from
'../../types/FileType';
8 import Statistics from
'../../types/Statistics';
9 import FileUtils from
'../../utils/FileUtils';
10 import { Storage
} from
'./Storage';
12 export class JsonFileStorage
extends Storage
{
13 private fd
: number | null = null;
15 constructor(storageUri
: string, logPrefix
: string) {
16 super(storageUri
, logPrefix
);
17 this.dbName
= this.storageUri
.pathname
;
20 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
21 this.checkPerformanceRecordsFile();
23 .lock(this.dbName
, { stale
: 5000, retries
: 3 })
24 .then(async (release
) => {
26 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
27 const performanceRecords
: Statistics
[] = fileData
28 ? (JSON
.parse(fileData
) as Statistics
[])
30 performanceRecords
.push(performanceStatistics
);
36 if (value
instanceof Map
) {
42 return value
as Statistics
;
49 FileUtils
.handleFileException(
51 FileType
.PerformanceRecords
,
53 error
as NodeJS
.ErrnoException
59 /* This is intentional */
66 this.fd
= fs
.openSync(this.dbName
, 'a+');
69 FileUtils
.handleFileException(
71 FileType
.PerformanceRecords
,
73 error
as NodeJS
.ErrnoException
78 public close(): void {
81 fs
.closeSync(this.fd
);
85 FileUtils
.handleFileException(
87 FileType
.PerformanceRecords
,
89 error
as NodeJS
.ErrnoException
94 private checkPerformanceRecordsFile(): void {
97 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`