1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import fs from
'node:fs';
4 import path 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
, ErrorUtils
, Utils
} 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
= 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 ErrorUtils
.handleFileException(
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 (!fs
.existsSync(path
.dirname(this.dbName
))) {
51 fs
.mkdirSync(path
.dirname(this.dbName
), { recursive
: true });
53 this.fd
= fs
.openSync(this.dbName
, 'a+');
56 ErrorUtils
.handleFileException(
58 FileType
.PerformanceRecords
,
59 error
as NodeJS
.ErrnoException
,
65 public close(): void {
68 fs
.closeSync(this.fd
);
72 ErrorUtils
.handleFileException(
74 FileType
.PerformanceRecords
,
75 error
as NodeJS
.ErrnoException
,
81 private checkPerformanceRecordsFile(): void {
84 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`