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 { FileType
, type Statistics
} from
'../../types';
8 import { AsyncLock
, AsyncLockType
, Constants
, ErrorUtils
, Utils
} from
'../../utils';
10 export class JsonFileStorage
extends Storage
{
11 private fd
: number | null = null;
13 constructor(storageUri
: string, logPrefix
: string) {
14 super(storageUri
, logPrefix
);
15 this.dbName
= this.storageUri
.pathname
;
18 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
19 this.checkPerformanceRecordsFile();
20 AsyncLock
.acquire(AsyncLockType
.performance
)
22 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
23 const performanceRecords
: Statistics
[] = fileData
24 ? (JSON
.parse(fileData
) as Statistics
[])
26 performanceRecords
.push(performanceStatistics
);
29 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
34 ErrorUtils
.handleFileException(
36 FileType
.PerformanceRecords
,
37 error
as NodeJS
.ErrnoException
,
42 AsyncLock
.release(AsyncLockType
.performance
).catch(Constants
.EMPTY_FUNCTION
);
48 if (Utils
.isNullOrUndefined(this?.fd
)) {
49 if (!fs
.existsSync(path
.dirname(this.dbName
))) {
50 fs
.mkdirSync(path
.dirname(this.dbName
), { recursive
: true });
52 this.fd
= fs
.openSync(this.dbName
, 'a+');
55 ErrorUtils
.handleFileException(
57 FileType
.PerformanceRecords
,
58 error
as NodeJS
.ErrnoException
,
64 public close(): void {
67 fs
.closeSync(this.fd
);
71 ErrorUtils
.handleFileException(
73 FileType
.PerformanceRecords
,
74 error
as NodeJS
.ErrnoException
,
80 private checkPerformanceRecordsFile(): void {
83 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`