17f5ad2f62ff92f3b06b7abb7b068208a62a325e
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { FileType } from '../../types/FileType';
4 import FileUtils from '../../utils/FileUtils';
5 import Statistics from '../../types/Statistics';
6 import { Storage } from './Storage';
7 import fs from 'fs';
8 import lockfile from 'proper-lockfile';
9
10 export class JsonFileStorage extends Storage {
11 private fd: number | null = null;
12
13 constructor(storageUri: string, logPrefix: string) {
14 super(storageUri, logPrefix);
15 this.dbName = this.storageUri.pathname;
16 }
17
18 public storePerformanceStatistics(performanceStatistics: Statistics): void {
19 this.checkPerformanceRecordsFile();
20 lockfile
21 .lock(this.dbName, { stale: 5000, retries: 3 })
22 .then(async (release) => {
23 try {
24 const fileData = fs.readFileSync(this.dbName, 'utf8');
25 const performanceRecords: Statistics[] = fileData
26 ? (JSON.parse(fileData) as Statistics[])
27 : [];
28 performanceRecords.push(performanceStatistics);
29 fs.writeFileSync(
30 this.dbName,
31 JSON.stringify(
32 performanceRecords,
33 (key, value) => {
34 if (value instanceof Map) {
35 return {
36 dataType: 'Map',
37 value: [...value],
38 };
39 }
40 return value as Statistics;
41 },
42 2
43 ),
44 'utf8'
45 );
46 } catch (error) {
47 FileUtils.handleFileException(
48 this.logPrefix,
49 FileType.PerformanceRecords,
50 this.dbName,
51 error as NodeJS.ErrnoException
52 );
53 }
54 await release();
55 })
56 .catch(() => {
57 /* This is intentional */
58 });
59 }
60
61 public open(): void {
62 try {
63 if (!this?.fd) {
64 this.fd = fs.openSync(this.dbName, 'a+');
65 }
66 } catch (error) {
67 FileUtils.handleFileException(
68 this.logPrefix,
69 FileType.PerformanceRecords,
70 this.dbName,
71 error as NodeJS.ErrnoException
72 );
73 }
74 }
75
76 public close(): void {
77 try {
78 if (this?.fd) {
79 fs.closeSync(this.fd);
80 this.fd = null;
81 }
82 } catch (error) {
83 FileUtils.handleFileException(
84 this.logPrefix,
85 FileType.PerformanceRecords,
86 this.dbName,
87 error as NodeJS.ErrnoException
88 );
89 }
90 }
91
92 private checkPerformanceRecordsFile(): void {
93 if (!this?.fd) {
94 throw new Error(
95 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
96 );
97 }
98 }
99 }