1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import fs from
'node:fs';
5 import lockfile from
'proper-lockfile';
7 import { FileType
, type Statistics
} from
'../../types';
8 import { Constants
, FileUtils
, Utils
} from
'../../utils';
9 import { Storage
} from
'../internal';
11 export class JsonFileStorage
extends Storage
{
12 private fd
: number | null = null;
14 constructor(storageUri
: string, logPrefix
: string) {
15 super(storageUri
, logPrefix
);
16 this.dbName
= this.storageUri
.pathname
;
19 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
20 this.checkPerformanceRecordsFile();
22 .lock(this.dbName
, { stale
: 5000, retries
: 3 })
23 .then(async (release
) => {
25 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
26 const performanceRecords
: Statistics
[] = fileData
27 ? (JSON
.parse(fileData
) as Statistics
[])
29 performanceRecords
.push(performanceStatistics
);
32 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
36 FileUtils
.handleFileException(
38 FileType
.PerformanceRecords
,
39 error
as NodeJS
.ErrnoException
,
45 .catch(Constants
.EMPTY_FUNCTION
);
50 if (Utils
.isNullOrUndefined(this?.fd
)) {
51 this.fd
= fs
.openSync(this.dbName
, 'a+');
54 FileUtils
.handleFileException(
56 FileType
.PerformanceRecords
,
57 error
as NodeJS
.ErrnoException
,
63 public close(): void {
66 fs
.closeSync(this.fd
);
70 FileUtils
.handleFileException(
72 FileType
.PerformanceRecords
,
73 error
as NodeJS
.ErrnoException
,
79 private checkPerformanceRecordsFile(): void {
82 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`