Storage: storage records in JSON file as an array to ease import.
[e-mobility-charging-stations-simulator.git] / src / utils / performance-storage / JSONFileStorage.ts
CommitLineData
72f041bd
JB
1import FileUtils from '../FileUtils';
2import Statistics from '../../types/Statistics';
3import { Storage } from './Storage';
4import fs from 'fs';
5import path from 'path';
6
7export class JSONFileStorage extends Storage {
8 constructor(storageURI: string, logPrefix: string) {
9 super(storageURI, logPrefix);
10 }
11
12 public storePerformanceStatistics(performanceStatistics: Statistics): void {
9ef75e34 13 const performanceJSONFilePath = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, ''));
b652b0c3
JB
14 if (!fs.existsSync(performanceJSONFilePath)) {
15 this.open(performanceJSONFilePath);
16 }
17 fs.readFile(performanceJSONFilePath, 'utf-8', (error, data) => {
18 if (error) {
19 FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, error);
20 } else {
21 const performanceRecords: Statistics[] = data ? JSON.parse(data.toString()) as Statistics[] : [];
22 performanceRecords.push(performanceStatistics);
23 fs.writeFile(performanceJSONFilePath, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => {
24 if (err) {
25 FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, err);
26 }
27 });
72f041bd
JB
28 }
29 });
30 }
b652b0c3
JB
31
32 private open(filePath: string): void {
33 try {
34 fs.openSync(filePath, 'w+');
35 } catch (error) {
36 FileUtils.handleFileException(this.logPrefix, 'Performance measurements', filePath, error);
37 }
38 }
72f041bd 39}