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