docs: refine README.md
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
... / ...
CommitLineData
1// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3import fs from 'node:fs';
4
5import lockfile from 'proper-lockfile';
6
7import { FileType, type Statistics } from '../../types';
8import { Constants, FileUtils, Utils } from '../../utils';
9import { Storage } from '../internal';
10
11export 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 lockfile
22 .lock(this.dbName, { stale: 5000, retries: 3 })
23 .then(async (release) => {
24 try {
25 const fileData = fs.readFileSync(this.dbName, 'utf8');
26 const performanceRecords: Statistics[] = fileData
27 ? (JSON.parse(fileData) as Statistics[])
28 : [];
29 performanceRecords.push(performanceStatistics);
30 fs.writeFileSync(
31 this.dbName,
32 Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
33 'utf8'
34 );
35 } catch (error) {
36 FileUtils.handleFileException(
37 this.dbName,
38 FileType.PerformanceRecords,
39 error as NodeJS.ErrnoException,
40 this.logPrefix
41 );
42 }
43 await release();
44 })
45 .catch(Constants.EMPTY_FUNCTION);
46 }
47
48 public open(): void {
49 try {
50 if (Utils.isNullOrUndefined(this?.fd)) {
51 this.fd = fs.openSync(this.dbName, 'a+');
52 }
53 } catch (error) {
54 FileUtils.handleFileException(
55 this.dbName,
56 FileType.PerformanceRecords,
57 error as NodeJS.ErrnoException,
58 this.logPrefix
59 );
60 }
61 }
62
63 public close(): void {
64 try {
65 if (this?.fd) {
66 fs.closeSync(this.fd);
67 this.fd = null;
68 }
69 } catch (error) {
70 FileUtils.handleFileException(
71 this.dbName,
72 FileType.PerformanceRecords,
73 error as NodeJS.ErrnoException,
74 this.logPrefix
75 );
76 }
77 }
78
79 private checkPerformanceRecordsFile(): void {
80 if (!this?.fd) {
81 throw new Error(
82 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
83 );
84 }
85 }
86}