fb7062674bb2ea14787a2d5eb0ff6646bab75d11
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 AsyncLock
.acquire(AsyncLockType
.performance
)
21 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
22 const performanceRecords
: Statistics
[] = fileData
23 ? (JSON
.parse(fileData
) as Statistics
[])
25 performanceRecords
.push(performanceStatistics
);
28 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
33 FileUtils
.handleFileException(
35 FileType
.PerformanceRecords
,
36 error
as NodeJS
.ErrnoException
,
41 AsyncLock
.release(AsyncLockType
.performance
).catch(Constants
.EMPTY_FUNCTION
);
47 if (Utils
.isNullOrUndefined(this?.fd
)) {
48 this.fd
= fs
.openSync(this.dbName
, 'a+');
51 FileUtils
.handleFileException(
53 FileType
.PerformanceRecords
,
54 error
as NodeJS
.ErrnoException
,
60 public close(): void {
63 fs
.closeSync(this.fd
);
67 FileUtils
.handleFileException(
69 FileType
.PerformanceRecords
,
70 error
as NodeJS
.ErrnoException
,
76 private checkPerformanceRecordsFile(): void {
79 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`