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