Add support for more DB engines via TypeORM
[e-mobility-charging-stations-simulator.git] / src / utils / performance-storage / JSONFileStorage.ts
CommitLineData
c27c3eee
JB
1// Copyright Jerome Benoit. 2021. All Rights Reserved.
2
2a370053 3import Constants from '../Constants';
72f041bd
JB
4import FileUtils from '../FileUtils';
5import Statistics from '../../types/Statistics';
6import { Storage } from './Storage';
7import fs from 'fs';
8import path from 'path';
9
10export class JSONFileStorage extends Storage {
2a370053
JB
11 private fd: number | null = null;
12
72f041bd
JB
13 constructor(storageURI: string, logPrefix: string) {
14 super(storageURI, logPrefix);
2a370053 15 this.dbName = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, ''));
72f041bd
JB
16 }
17
18 public storePerformanceStatistics(performanceStatistics: Statistics): void {
2a370053
JB
19 this.checkPerformanceRecordsFile();
20 fs.readFile(this.dbName, 'utf-8', (error, data) => {
b652b0c3 21 if (error) {
2a370053 22 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error);
b652b0c3 23 } else {
2a370053 24 const performanceRecords: Statistics[] = data ? JSON.parse(data) as Statistics[] : [];
b652b0c3 25 performanceRecords.push(performanceStatistics);
2a370053 26 fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => {
b652b0c3 27 if (err) {
2a370053 28 FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, err);
b652b0c3
JB
29 }
30 });
72f041bd
JB
31 }
32 });
33 }
b652b0c3 34
2a370053 35 public open(): void {
b652b0c3 36 try {
2a370053 37 this.fd = fs.openSync(this.dbName, 'a+');
b652b0c3 38 } catch (error) {
2a370053
JB
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`);
b652b0c3
JB
57 }
58 }
72f041bd 59}