fix: various fixes to files handling and their content caching
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import fs from 'node:fs';
4 import path from 'node:path';
5
6 import { Storage } from './Storage';
7 import { BaseError } from '../../exception';
8 import { FileType, type Statistics } from '../../types';
9 import { AsyncLock, AsyncLockType, Constants, ErrorUtils, Utils } from '../../utils';
10
11 export class JsonFileStorage extends Storage {
12 private fd: number | null = null;
13
14 constructor(storageUri: string, logPrefix: string) {
15 super(storageUri, logPrefix);
16 this.dbName = this.storageUri.pathname;
17 }
18
19 public storePerformanceStatistics(performanceStatistics: Statistics): void {
20 this.checkPerformanceRecordsFile();
21 AsyncLock.acquire(AsyncLockType.performance)
22 .then(() => {
23 const fileData = fs.readFileSync(this.dbName, 'utf8');
24 const performanceRecords: Statistics[] = fileData
25 ? (JSON.parse(fileData) as Statistics[])
26 : [];
27 performanceRecords.push(performanceStatistics);
28 fs.writeFileSync(
29 this.dbName,
30 Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
31 'utf8'
32 );
33 })
34 .catch((error) => {
35 ErrorUtils.handleFileException(
36 this.dbName,
37 FileType.PerformanceRecords,
38 error as NodeJS.ErrnoException,
39 this.logPrefix
40 );
41 })
42 .finally(() => {
43 AsyncLock.release(AsyncLockType.performance).catch(Constants.EMPTY_FUNCTION);
44 });
45 }
46
47 public open(): void {
48 try {
49 if (Utils.isNullOrUndefined(this?.fd)) {
50 if (!fs.existsSync(path.dirname(this.dbName))) {
51 fs.mkdirSync(path.dirname(this.dbName), { recursive: true });
52 }
53 this.fd = fs.openSync(this.dbName, 'a+');
54 }
55 } catch (error) {
56 ErrorUtils.handleFileException(
57 this.dbName,
58 FileType.PerformanceRecords,
59 error as NodeJS.ErrnoException,
60 this.logPrefix
61 );
62 }
63 }
64
65 public close(): void {
66 try {
67 if (this?.fd) {
68 fs.closeSync(this.fd);
69 this.fd = null;
70 }
71 } catch (error) {
72 ErrorUtils.handleFileException(
73 this.dbName,
74 FileType.PerformanceRecords,
75 error as NodeJS.ErrnoException,
76 this.logPrefix
77 );
78 }
79 }
80
81 private checkPerformanceRecordsFile(): void {
82 if (!this?.fd) {
83 throw new BaseError(
84 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
85 );
86 }
87 }
88 }