Apply prettier formating
[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 9
100a5301 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();
e7aeea18
JB
20 lockfile
21 .lock(this.dbName, { stale: 5000, retries: 3 })
c63c21bc
JB
22 .then(async (release) => {
23 try {
24 const fileData = fs.readFileSync(this.dbName, 'utf8');
e7aeea18
JB
25 const performanceRecords: Statistics[] = fileData
26 ? (JSON.parse(fileData) as Statistics[])
27 : [];
c63c21bc 28 performanceRecords.push(performanceStatistics);
1830ad42
JB
29 fs.writeFileSync(
30 this.dbName,
e7aeea18
JB
31 JSON.stringify(
32 performanceRecords,
ff4b895e
JB
33 (key, value) => {
34 if (value instanceof Map) {
35 return {
36 dataType: 'Map',
e7aeea18 37 value: [...value],
ff4b895e
JB
38 };
39 }
40 return value as Statistics;
41 },
e7aeea18
JB
42 2
43 ),
1830ad42
JB
44 'utf8'
45 );
c63c21bc 46 } catch (error) {
e7aeea18
JB
47 FileUtils.handleFileException(
48 this.logPrefix,
49 Constants.PERFORMANCE_RECORDS_FILETYPE,
50 this.dbName,
51 error as NodeJS.ErrnoException
52 );
c63c21bc
JB
53 }
54 await release();
55 })
e7aeea18
JB
56 .catch(() => {
57 /* This is intentional */
58 });
72f041bd 59 }
b652b0c3 60
2a370053 61 public open(): void {
b652b0c3 62 try {
a6ceb16a
JB
63 if (!this?.fd) {
64 this.fd = fs.openSync(this.dbName, 'a+');
65 }
b652b0c3 66 } catch (error) {
e7aeea18
JB
67 FileUtils.handleFileException(
68 this.logPrefix,
69 Constants.PERFORMANCE_RECORDS_FILETYPE,
70 this.dbName,
71 error as NodeJS.ErrnoException
72 );
2a370053
JB
73 }
74 }
75
76 public close(): void {
77 try {
a6ceb16a 78 if (this?.fd) {
2a370053
JB
79 fs.closeSync(this.fd);
80 this.fd = null;
81 }
82 } catch (error) {
e7aeea18
JB
83 FileUtils.handleFileException(
84 this.logPrefix,
85 Constants.PERFORMANCE_RECORDS_FILETYPE,
86 this.dbName,
87 error as NodeJS.ErrnoException
88 );
2a370053
JB
89 }
90 }
91
92 private checkPerformanceRecordsFile(): void {
73d09045 93 if (!this?.fd) {
e7aeea18
JB
94 throw new Error(
95 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
96 );
b652b0c3
JB
97 }
98 }
72f041bd 99}