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 JB |
18 | this.checkPerformanceRecordsFile(); |
19 | fs.readFile(this.dbName, 'utf-8', (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); |
2a370053 | 25 | fs.writeFile(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf-8', (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 { |
2a370053 | 36 | this.fd = fs.openSync(this.dbName, 'a+'); |
b652b0c3 | 37 | } catch (error) { |
2a370053 JB |
38 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
39 | } | |
40 | } | |
41 | ||
42 | public close(): void { | |
43 | try { | |
44 | if (this.fd) { | |
45 | fs.closeSync(this.fd); | |
46 | this.fd = null; | |
47 | } | |
48 | } catch (error) { | |
49 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); | |
50 | } | |
51 | } | |
52 | ||
53 | private checkPerformanceRecordsFile(): void { | |
54 | if (!this.fd) { | |
55 | throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`); | |
b652b0c3 JB |
56 | } |
57 | } | |
72f041bd | 58 | } |