refactor: cleanup eslint configuration
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
CommitLineData
a19b897d 1// Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
c27c3eee 2
66a7748d
JB
3import { closeSync, existsSync, mkdirSync, openSync, writeSync } from 'node:fs'
4import { dirname } from 'node:path'
8114d10e 5
66a7748d
JB
6import { BaseError } from '../../exception/index.js'
7import { FileType, type Statistics } from '../../types/index.js'
9bf0ef23
JB
8import {
9 AsyncLock,
10 AsyncLockType,
4c3f6c20
JB
11 handleFileException,
12 JSONStringifyWithMapSupport
66a7748d 13} from '../../utils/index.js'
4c3f6c20 14import { Storage } from './Storage.js'
72f041bd 15
100a5301 16export class JsonFileStorage extends Storage {
66a7748d 17 private fd?: number
2a370053 18
66a7748d
JB
19 constructor (storageUri: string, logPrefix: string) {
20 super(storageUri, logPrefix)
21 this.dbName = this.storageUri.pathname
72f041bd
JB
22 }
23
66a7748d 24 public storePerformanceStatistics (performanceStatistics: Statistics): void {
a66bbcfe 25 this.setPerformanceStatistics(performanceStatistics)
66a7748d 26 this.checkPerformanceRecordsFile()
0ebf7c2e 27 AsyncLock.runExclusive(AsyncLockType.performance, () => {
0ebf7c2e 28 writeSync(
66a7748d 29 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
0ebf7c2e 30 this.fd!,
a66bbcfe 31 JSONStringifyWithMapSupport([...this.getPerformanceStatistics()], 2),
0ebf7c2e 32 0,
66a7748d
JB
33 'utf8'
34 )
a974c8e4 35 }).catch(error => {
0ebf7c2e
JB
36 handleFileException(
37 this.dbName,
38 FileType.PerformanceRecords,
39 error as NodeJS.ErrnoException,
66a7748d
JB
40 this.logPrefix
41 )
42 })
72f041bd 43 }
b652b0c3 44
66a7748d 45 public open (): void {
b652b0c3 46 try {
5199f9fd 47 if (this.fd == null) {
d972af76 48 if (!existsSync(dirname(this.dbName))) {
66a7748d 49 mkdirSync(dirname(this.dbName), { recursive: true })
f682b2dc 50 }
66a7748d 51 this.fd = openSync(this.dbName, 'w')
a6ceb16a 52 }
b652b0c3 53 } catch (error) {
fa5995d6 54 handleFileException(
e7aeea18 55 this.dbName,
7164966d
JB
56 FileType.PerformanceRecords,
57 error as NodeJS.ErrnoException,
66a7748d
JB
58 this.logPrefix
59 )
2a370053
JB
60 }
61 }
62
66a7748d 63 public close (): void {
a66bbcfe 64 this.clearPerformanceStatistics()
2a370053 65 try {
5199f9fd 66 if (this.fd != null) {
66a7748d 67 closeSync(this.fd)
5199f9fd 68 delete this.fd
2a370053
JB
69 }
70 } catch (error) {
fa5995d6 71 handleFileException(
e7aeea18 72 this.dbName,
7164966d
JB
73 FileType.PerformanceRecords,
74 error as NodeJS.ErrnoException,
66a7748d
JB
75 this.logPrefix
76 )
2a370053
JB
77 }
78 }
79
66a7748d 80 private checkPerformanceRecordsFile (): void {
5199f9fd 81 if (this.fd == null) {
7b5dbe91 82 throw new BaseError(
66a7748d
JB
83 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
84 )
b652b0c3
JB
85 }
86 }
72f041bd 87}