Commit | Line | Data |
---|---|---|
c27c3eee JB |
1 | // Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
a6b3c6c3 JB |
3 | import Constants from '../../utils/Constants'; |
4 | import FileUtils from '../../utils/FileUtils'; | |
72f041bd JB |
5 | import Statistics from '../../types/Statistics'; |
6 | import { Storage } from './Storage'; | |
7 | import fs from 'fs'; | |
72f041bd JB |
8 | |
9 | export class JSONFileStorage extends Storage { | |
2a370053 JB |
10 | private fd: number | null = null; |
11 | ||
72f041bd JB |
12 | constructor(storageURI: string, logPrefix: string) { |
13 | super(storageURI, logPrefix); | |
a6b3c6c3 | 14 | this.dbName = this.storageURI.pathname; |
72f041bd JB |
15 | } |
16 | ||
17 | public storePerformanceStatistics(performanceStatistics: Statistics): void { | |
2a370053 | 18 | this.checkPerformanceRecordsFile(); |
247f55f4 | 19 | fs.readFile(this.dbName, 'utf8', (error, data) => { |
b652b0c3 | 20 | if (error) { |
2a370053 | 21 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
b652b0c3 | 22 | } else { |
2a370053 | 23 | const performanceRecords: Statistics[] = data ? JSON.parse(data) as Statistics[] : []; |
b652b0c3 | 24 | performanceRecords.push(performanceStatistics); |
247f55f4 | 25 | fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf8', (err) => { |
b652b0c3 | 26 | if (err) { |
2a370053 | 27 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, err); |
b652b0c3 JB |
28 | } |
29 | }); | |
72f041bd JB |
30 | } |
31 | }); | |
32 | } | |
b652b0c3 | 33 | |
2a370053 | 34 | public open(): void { |
b652b0c3 | 35 | try { |
a6ceb16a JB |
36 | if (!this?.fd) { |
37 | this.fd = fs.openSync(this.dbName, 'a+'); | |
38 | } | |
b652b0c3 | 39 | } catch (error) { |
2a370053 JB |
40 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
41 | } | |
42 | } | |
43 | ||
44 | public close(): void { | |
45 | try { | |
a6ceb16a | 46 | if (this?.fd) { |
2a370053 JB |
47 | fs.closeSync(this.fd); |
48 | this.fd = null; | |
49 | } | |
50 | } catch (error) { | |
51 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); | |
52 | } | |
53 | } | |
54 | ||
55 | private checkPerformanceRecordsFile(): void { | |
73d09045 | 56 | if (!this?.fd) { |
2a370053 | 57 | throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`); |
b652b0c3 JB |
58 | } |
59 | } | |
72f041bd | 60 | } |