refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
CommitLineData
edd13439 1// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c27c3eee 2
130783a7 3import fs from 'node:fs';
8114d10e
JB
4
5import lockfile from 'proper-lockfile';
6
268a74bb 7import { FileType, type Statistics } from '../../types';
60a74391 8import { FileUtils, Utils } from '../../utils';
2896e06d 9import { Storage } from '../internal';
72f041bd 10
100a5301 11export class JsonFileStorage extends Storage {
2a370053
JB
12 private fd: number | null = null;
13
1f5df42a
JB
14 constructor(storageUri: string, logPrefix: string) {
15 super(storageUri, logPrefix);
16 this.dbName = this.storageUri.pathname;
72f041bd
JB
17 }
18
19 public storePerformanceStatistics(performanceStatistics: Statistics): void {
2a370053 20 this.checkPerformanceRecordsFile();
e7aeea18
JB
21 lockfile
22 .lock(this.dbName, { stale: 5000, retries: 3 })
72092cfc 23 .then(async (release) => {
c63c21bc
JB
24 try {
25 const fileData = fs.readFileSync(this.dbName, 'utf8');
e7aeea18
JB
26 const performanceRecords: Statistics[] = fileData
27 ? (JSON.parse(fileData) as Statistics[])
28 : [];
c63c21bc 29 performanceRecords.push(performanceStatistics);
1830ad42
JB
30 fs.writeFileSync(
31 this.dbName,
fe791818 32 Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
1830ad42
JB
33 'utf8'
34 );
c63c21bc 35 } catch (error) {
e7aeea18 36 FileUtils.handleFileException(
e7aeea18 37 this.dbName,
7164966d
JB
38 FileType.PerformanceRecords,
39 error as NodeJS.ErrnoException,
40 this.logPrefix
e7aeea18 41 );
c63c21bc
JB
42 }
43 await release();
44 })
e7aeea18
JB
45 .catch(() => {
46 /* This is intentional */
47 });
72f041bd 48 }
b652b0c3 49
2a370053 50 public open(): void {
b652b0c3 51 try {
b40b5cb3 52 if (this?.fd === undefined || this?.fd === null) {
a6ceb16a
JB
53 this.fd = fs.openSync(this.dbName, 'a+');
54 }
b652b0c3 55 } catch (error) {
e7aeea18 56 FileUtils.handleFileException(
e7aeea18 57 this.dbName,
7164966d
JB
58 FileType.PerformanceRecords,
59 error as NodeJS.ErrnoException,
60 this.logPrefix
e7aeea18 61 );
2a370053
JB
62 }
63 }
64
65 public close(): void {
66 try {
a6ceb16a 67 if (this?.fd) {
2a370053
JB
68 fs.closeSync(this.fd);
69 this.fd = null;
70 }
71 } catch (error) {
e7aeea18 72 FileUtils.handleFileException(
e7aeea18 73 this.dbName,
7164966d
JB
74 FileType.PerformanceRecords,
75 error as NodeJS.ErrnoException,
76 this.logPrefix
e7aeea18 77 );
2a370053
JB
78 }
79 }
80
81 private checkPerformanceRecordsFile(): void {
73d09045 82 if (!this?.fd) {
e7aeea18
JB
83 throw new Error(
84 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
85 );
b652b0c3
JB
86 }
87 }
72f041bd 88}