build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
CommitLineData
edd13439 1// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c27c3eee 2
130783a7 3import fs from 'node:fs';
8114d10e 4
268a74bb 5import { FileType, type Statistics } from '../../types';
1227a6f1 6import { AsyncLock, AsyncLockType, Constants, FileUtils, Utils } from '../../utils';
2896e06d 7import { Storage } from '../internal';
72f041bd 8
100a5301 9export class JsonFileStorage extends Storage {
2a370053
JB
10 private fd: number | null = null;
11
1f5df42a
JB
12 constructor(storageUri: string, logPrefix: string) {
13 super(storageUri, logPrefix);
14 this.dbName = this.storageUri.pathname;
72f041bd
JB
15 }
16
17 public storePerformanceStatistics(performanceStatistics: Statistics): void {
2a370053 18 this.checkPerformanceRecordsFile();
dd485b56 19 AsyncLock.acquire(AsyncLockType.performance)
1227a6f1
JB
20 .then(() => {
21 const fileData = fs.readFileSync(this.dbName, 'utf8');
22 const performanceRecords: Statistics[] = fileData
23 ? (JSON.parse(fileData) as Statistics[])
24 : [];
25 performanceRecords.push(performanceStatistics);
26 fs.writeFileSync(
27 this.dbName,
28 Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
29 'utf8'
30 );
31 })
32 .catch((error) => {
33 FileUtils.handleFileException(
34 this.dbName,
35 FileType.PerformanceRecords,
36 error as NodeJS.ErrnoException,
37 this.logPrefix
38 );
c63c21bc 39 })
1227a6f1 40 .finally(() => {
dd485b56 41 AsyncLock.release(AsyncLockType.performance).catch(Constants.EMPTY_FUNCTION);
1227a6f1 42 });
72f041bd 43 }
b652b0c3 44
2a370053 45 public open(): void {
b652b0c3 46 try {
4c5e87ae 47 if (Utils.isNullOrUndefined(this?.fd)) {
a6ceb16a
JB
48 this.fd = fs.openSync(this.dbName, 'a+');
49 }
b652b0c3 50 } catch (error) {
e7aeea18 51 FileUtils.handleFileException(
e7aeea18 52 this.dbName,
7164966d
JB
53 FileType.PerformanceRecords,
54 error as NodeJS.ErrnoException,
55 this.logPrefix
e7aeea18 56 );
2a370053
JB
57 }
58 }
59
60 public close(): void {
61 try {
a6ceb16a 62 if (this?.fd) {
2a370053
JB
63 fs.closeSync(this.fd);
64 this.fd = null;
65 }
66 } catch (error) {
e7aeea18 67 FileUtils.handleFileException(
e7aeea18 68 this.dbName,
7164966d
JB
69 FileType.PerformanceRecords,
70 error as NodeJS.ErrnoException,
71 this.logPrefix
e7aeea18 72 );
2a370053
JB
73 }
74 }
75
76 private checkPerformanceRecordsFile(): void {
73d09045 77 if (!this?.fd) {
e7aeea18
JB
78 throw new Error(
79 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
80 );
b652b0c3
JB
81 }
82 }
72f041bd 83}