Version 1.1.37
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JSONFileStorage.ts
CommitLineData
c27c3eee
JB
1// Copyright Jerome Benoit. 2021. All Rights Reserved.
2
a6b3c6c3
JB
3import Constants from '../../utils/Constants';
4import FileUtils from '../../utils/FileUtils';
72f041bd
JB
5import Statistics from '../../types/Statistics';
6import { Storage } from './Storage';
7import fs from 'fs';
c63c21bc 8import lockfile from 'proper-lockfile';
72f041bd
JB
9
10export class JSONFileStorage extends Storage {
2a370053
JB
11 private fd: number | null = null;
12
1f5df42a
JB
13 constructor(storageUri: string, logPrefix: string) {
14 super(storageUri, logPrefix);
15 this.dbName = this.storageUri.pathname;
72f041bd
JB
16 }
17
18 public storePerformanceStatistics(performanceStatistics: Statistics): void {
2a370053 19 this.checkPerformanceRecordsFile();
c63c21bc
JB
20 lockfile.lock(this.dbName, { stale: 5000, retries: 3 })
21 .then(async (release) => {
22 try {
23 const fileData = fs.readFileSync(this.dbName, 'utf8');
24 const performanceRecords: Statistics[] = fileData ? JSON.parse(fileData) as Statistics[] : [];
25 performanceRecords.push(performanceStatistics);
1830ad42
JB
26 fs.writeFileSync(
27 this.dbName,
ff4b895e
JB
28 JSON.stringify(performanceRecords,
29 (key, value) => {
30 if (value instanceof Map) {
31 return {
32 dataType: 'Map',
33 value: [...value]
34 };
35 }
36 return value as Statistics;
37 },
38 2),
1830ad42
JB
39 'utf8'
40 );
c63c21bc 41 } catch (error) {
dc100e97 42 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error as NodeJS.ErrnoException);
c63c21bc
JB
43 }
44 await release();
45 })
68a8d1bb 46 .catch(() => { /* This is intentional */ });
72f041bd 47 }
b652b0c3 48
2a370053 49 public open(): void {
b652b0c3 50 try {
a6ceb16a
JB
51 if (!this?.fd) {
52 this.fd = fs.openSync(this.dbName, 'a+');
53 }
b652b0c3 54 } catch (error) {
dc100e97 55 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error as NodeJS.ErrnoException);
2a370053
JB
56 }
57 }
58
59 public close(): void {
60 try {
a6ceb16a 61 if (this?.fd) {
2a370053
JB
62 fs.closeSync(this.fd);
63 this.fd = null;
64 }
65 } catch (error) {
dc100e97 66 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error as NodeJS.ErrnoException);
2a370053
JB
67 }
68 }
69
70 private checkPerformanceRecordsFile(): void {
73d09045 71 if (!this?.fd) {
2a370053 72 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);
b652b0c3
JB
73 }
74 }
72f041bd 75}