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
, MapStringifyFormat
, type Statistics
} from
'../../types/index.js'
8 import { AsyncLock
, AsyncLockType
, handleFileException
, JSONStringify
} from
'../../utils/index.js'
9 import { Storage
} from
'./Storage.js'
11 export class JsonFileStorage
extends Storage
{
14 constructor (storageUri
: string, logPrefix
: string) {
15 super(storageUri
, logPrefix
)
16 this.dbName
= this.storageUri
.pathname
19 public storePerformanceStatistics (performanceStatistics
: Statistics
): void {
20 this.setPerformanceStatistics(performanceStatistics
)
21 this.checkPerformanceRecordsFile()
22 AsyncLock
.runExclusive(AsyncLockType
.performance
, () => {
24 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
26 JSONStringify([...this.getPerformanceStatistics()], 2, MapStringifyFormat
.object
),
30 }).catch((error
: unknown
) => {
33 FileType
.PerformanceRecords
,
34 error
as NodeJS
.ErrnoException
,
40 public open (): void {
42 if (this.fd
== null) {
43 if (!existsSync(dirname(this.dbName
))) {
44 mkdirSync(dirname(this.dbName
), { recursive
: true })
46 this.fd
= openSync(this.dbName
, 'w')
51 FileType
.PerformanceRecords
,
52 error
as NodeJS
.ErrnoException
,
58 public close (): void {
59 this.clearPerformanceStatistics()
61 if (this.fd
!= null) {
68 FileType
.PerformanceRecords
,
69 error
as NodeJS
.ErrnoException
,
75 private checkPerformanceRecordsFile (): void {
76 if (this.fd
== null) {
78 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`