1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { closeSync
, existsSync
, mkdirSync
, openSync
, writeSync
} from
'node:fs'
4 import { dirname
} from
'node:path'
6 import { BaseError
} from
'../../exception/index.js'
7 import { FileType
, type Statistics
} from
'../../types/index.js'
12 JSONStringifyWithMapSupport
13 } from
'../../utils/index.js'
14 import { Storage
} from
'./Storage.js'
16 export class JsonFileStorage
extends Storage
{
19 constructor (storageUri
: string, logPrefix
: string) {
20 super(storageUri
, logPrefix
)
21 this.dbName
= this.storageUri
.pathname
24 public storePerformanceStatistics (performanceStatistics
: Statistics
): void {
25 this.setPerformanceStatistics(performanceStatistics
)
26 this.checkPerformanceRecordsFile()
27 AsyncLock
.runExclusive(AsyncLockType
.performance
, () => {
29 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
31 JSONStringifyWithMapSupport([...this.getPerformanceStatistics()], 2),
38 FileType
.PerformanceRecords
,
39 error
as NodeJS
.ErrnoException
,
45 public open (): void {
47 if (this.fd
== null) {
48 if (!existsSync(dirname(this.dbName
))) {
49 mkdirSync(dirname(this.dbName
), { recursive
: true })
51 this.fd
= openSync(this.dbName
, 'w')
56 FileType
.PerformanceRecords
,
57 error
as NodeJS
.ErrnoException
,
63 public close (): void {
64 this.clearPerformanceStatistics()
66 if (this.fd
!= null) {
73 FileType
.PerformanceRecords
,
74 error
as NodeJS
.ErrnoException
,
80 private checkPerformanceRecordsFile (): void {
81 if (this.fd
== null) {
83 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`