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