44340cc4e425a9b1faf5f520a9f69e344f8fab77
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 { 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
,
46 /* This is intentional */
52 if (Utils
.isNullOrUndefined(this?.fd
)) {
53 this.fd
= fs
.openSync(this.dbName
, 'a+');
56 FileUtils
.handleFileException(
58 FileType
.PerformanceRecords
,
59 error
as NodeJS
.ErrnoException
,
65 public close(): void {
68 fs
.closeSync(this.fd
);
72 FileUtils
.handleFileException(
74 FileType
.PerformanceRecords
,
75 error
as NodeJS
.ErrnoException
,
81 private checkPerformanceRecordsFile(): void {
84 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`