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