1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import fs from
'node:fs';
5 import { FileType
, type Statistics
} from
'../../types';
6 import { AsyncLock
, AsyncLockType
, Constants
, FileUtils
, Utils
} from
'../../utils';
7 import { Storage
} from
'../internal';
9 export class JsonFileStorage
extends Storage
{
10 private fd
: number | null = null;
12 constructor(storageUri
: string, logPrefix
: string) {
13 super(storageUri
, logPrefix
);
14 this.dbName
= this.storageUri
.pathname
;
17 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
18 this.checkPerformanceRecordsFile();
19 const asyncLock
= AsyncLock
.getInstance(AsyncLockType
.performance
);
23 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
24 const performanceRecords
: Statistics
[] = fileData
25 ? (JSON
.parse(fileData
) as Statistics
[])
27 performanceRecords
.push(performanceStatistics
);
30 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
35 FileUtils
.handleFileException(
37 FileType
.PerformanceRecords
,
38 error
as NodeJS
.ErrnoException
,
43 asyncLock
.release().catch(Constants
.EMPTY_FUNCTION
);
49 if (Utils
.isNullOrUndefined(this?.fd
)) {
50 this.fd
= fs
.openSync(this.dbName
, 'a+');
53 FileUtils
.handleFileException(
55 FileType
.PerformanceRecords
,
56 error
as NodeJS
.ErrnoException
,
62 public close(): void {
65 fs
.closeSync(this.fd
);
69 FileUtils
.handleFileException(
71 FileType
.PerformanceRecords
,
72 error
as NodeJS
.ErrnoException
,
78 private checkPerformanceRecordsFile(): void {
81 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`