Throw an error in the template does not have default required mesurand
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JSONFileStorage.ts
1 // Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import Constants from '../../utils/Constants';
4 import FileUtils from '../../utils/FileUtils';
5 import Statistics from '../../types/Statistics';
6 import { Storage } from './Storage';
7 import fs from 'fs';
8
9 export class JSONFileStorage extends Storage {
10 private fd: number | null = null;
11
12 constructor(storageURI: string, logPrefix: string) {
13 super(storageURI, logPrefix);
14 this.dbName = this.storageURI.pathname;
15 }
16
17 public storePerformanceStatistics(performanceStatistics: Statistics): void {
18 this.checkPerformanceRecordsFile();
19 fs.readFile(this.dbName, 'utf-8', (error, data) => {
20 if (error) {
21 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
22 } else {
23 const performanceRecords: Statistics[] = data ? JSON.parse(data) as Statistics[] : [];
24 performanceRecords.push(performanceStatistics);
25 fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => {
26 if (err) {
27 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, err);
28 }
29 });
30 }
31 });
32 }
33
34 public open(): void {
35 try {
36 this.fd = fs.openSync(this.dbName, 'a+');
37 } catch (error) {
38 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
39 }
40 }
41
42 public close(): void {
43 try {
44 if (this.fd) {
45 fs.closeSync(this.fd);
46 this.fd = null;
47 }
48 } catch (error) {
49 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
50 }
51 }
52
53 private checkPerformanceRecordsFile(): void {
54 if (!this.fd) {
55 throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`);
56 }
57 }
58 }