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';
13 JSONStringifyWithMapSupport
,
18 export class JsonFileStorage
extends Storage
{
19 private fd
: number | null = null;
21 constructor(storageUri
: string, logPrefix
: string) {
22 super(storageUri
, logPrefix
);
23 this.dbName
= this.storageUri
.pathname
;
26 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
27 this.checkPerformanceRecordsFile();
28 AsyncLock
.acquire(AsyncLockType
.performance
)
30 const fileData
= readFileSync(this.dbName
, 'utf8');
31 const performanceRecords
: Statistics
[] = fileData
32 ? (JSON
.parse(fileData
) as Statistics
[])
34 performanceRecords
.push(performanceStatistics
);
35 writeFileSync(this.dbName
, JSONStringifyWithMapSupport(performanceRecords
, 2), 'utf8');
40 FileType
.PerformanceRecords
,
41 error
as NodeJS
.ErrnoException
,
46 AsyncLock
.release(AsyncLockType
.performance
).catch(Constants
.EMPTY_FUNCTION
);
52 if (isNullOrUndefined(this?.fd
)) {
53 if (!existsSync(dirname(this.dbName
))) {
54 mkdirSync(dirname(this.dbName
), { recursive
: true });
56 this.fd
= openSync(this.dbName
, 'a+');
61 FileType
.PerformanceRecords
,
62 error
as NodeJS
.ErrnoException
,
68 public close(): void {
77 FileType
.PerformanceRecords
,
78 error
as NodeJS
.ErrnoException
,
84 private checkPerformanceRecordsFile(): void {
87 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`,