Apply dependencies update
[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
72f041bd
JB
13 constructor(storageURI: string, logPrefix: string) {
14 super(storageURI, logPrefix);
a6b3c6c3 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);
26 fs.writeFileSync(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf8');
27 } catch (error) {
28 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
29 }
30 await release();
31 })
68a8d1bb 32 .catch(() => { /* This is intentional */ });
72f041bd 33 }
b652b0c3 34
2a370053 35 public open(): void {
b652b0c3 36 try {
a6ceb16a
JB
37 if (!this?.fd) {
38 this.fd = fs.openSync(this.dbName, 'a+');
39 }
b652b0c3 40 } catch (error) {
2a370053
JB
41 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
42 }
43 }
44
45 public close(): void {
46 try {
a6ceb16a 47 if (this?.fd) {
2a370053
JB
48 fs.closeSync(this.fd);
49 this.fd = null;
50 }
51 } catch (error) {
52 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
53 }
54 }
55
56 private checkPerformanceRecordsFile(): void {
73d09045 57 if (!this?.fd) {
2a370053 58 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);
b652b0c3
JB
59 }
60 }
72f041bd 61}