1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { FileType
} from
'../../types/FileType';
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();
21 .lock(this.dbName
, { stale
: 5000, retries
: 3 })
22 .then(async (release
) => {
24 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
25 const performanceRecords
: Statistics
[] = fileData
26 ? (JSON
.parse(fileData
) as Statistics
[])
28 performanceRecords
.push(performanceStatistics
);
34 if (value
instanceof Map
) {
40 return value
as Statistics
;
47 FileUtils
.handleFileException(
49 FileType
.PerformanceRecords
,
51 error
as NodeJS
.ErrnoException
57 /* This is intentional */
64 this.fd
= fs
.openSync(this.dbName
, 'a+');
67 FileUtils
.handleFileException(
69 FileType
.PerformanceRecords
,
71 error
as NodeJS
.ErrnoException
76 public close(): void {
79 fs
.closeSync(this.fd
);
83 FileUtils
.handleFileException(
85 FileType
.PerformanceRecords
,
87 error
as NodeJS
.ErrnoException
92 private checkPerformanceRecordsFile(): void {
95 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`