Apply dependencies update
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JSONFileStorage.ts
... / ...
CommitLineData
1// Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3import Constants from '../../utils/Constants';
4import FileUtils from '../../utils/FileUtils';
5import Statistics from '../../types/Statistics';
6import { Storage } from './Storage';
7import fs from 'fs';
8import lockfile from 'proper-lockfile';
9
10export 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.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 })
32 .catch(() => { /* This is intentional */ });
33 }
34
35 public open(): void {
36 try {
37 if (!this?.fd) {
38 this.fd = fs.openSync(this.dbName, 'a+');
39 }
40 } catch (error) {
41 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
42 }
43 }
44
45 public close(): void {
46 try {
47 if (this?.fd) {
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 {
57 if (!this?.fd) {
58 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);
59 }
60 }
61}