1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { closeSync
, existsSync
, mkdirSync
, openSync
, readFileSync
, writeFileSync
} from
'node:fs';
4 import { dirname
} from
'node:path';
6 import { Storage
} from
'./Storage';
7 import { BaseError
} from
'../../exception';
8 import { FileType
, type Statistics
} from
'../../types';
9 import { AsyncLock
, AsyncLockType
, Constants
, Utils
, handleFileException
} from
'../../utils';
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();
21 AsyncLock
.acquire(AsyncLockType
.performance
)
23 const fileData
= readFileSync(this.dbName
, 'utf8');
24 const performanceRecords
: Statistics
[] = fileData
25 ? (JSON
.parse(fileData
) as Statistics
[])
27 performanceRecords
.push(performanceStatistics
);
30 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
37 FileType
.PerformanceRecords
,
38 error
as NodeJS
.ErrnoException
,
43 AsyncLock
.release(AsyncLockType
.performance
).catch(Constants
.EMPTY_FUNCTION
);
49 if (Utils
.isNullOrUndefined(this?.fd
)) {
50 if (!existsSync(dirname(this.dbName
))) {
51 mkdirSync(dirname(this.dbName
), { recursive
: true });
53 this.fd
= openSync(this.dbName
, 'a+');
58 FileType
.PerformanceRecords
,
59 error
as NodeJS
.ErrnoException
,
65 public close(): void {
74 FileType
.PerformanceRecords
,
75 error
as NodeJS
.ErrnoException
,
81 private checkPerformanceRecordsFile(): void {
84 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`