| 1 | import FileUtils from '../FileUtils'; |
| 2 | import Statistics from '../../types/Statistics'; |
| 3 | import { Storage } from './Storage'; |
| 4 | import fs from 'fs'; |
| 5 | import path from 'path'; |
| 6 | |
| 7 | export class JSONFileStorage extends Storage { |
| 8 | constructor(storageURI: string, logPrefix: string) { |
| 9 | super(storageURI, logPrefix); |
| 10 | } |
| 11 | |
| 12 | public storePerformanceStatistics(performanceStatistics: Statistics): void { |
| 13 | const performanceJSONFilePath = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '')); |
| 14 | if (!fs.existsSync(performanceJSONFilePath)) { |
| 15 | this.open(performanceJSONFilePath); |
| 16 | } |
| 17 | fs.readFile(performanceJSONFilePath, 'utf-8', (error, data) => { |
| 18 | if (error) { |
| 19 | FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, error); |
| 20 | } else { |
| 21 | const performanceRecords: Statistics[] = data ? JSON.parse(data.toString()) as Statistics[] : []; |
| 22 | performanceRecords.push(performanceStatistics); |
| 23 | fs.writeFile(performanceJSONFilePath, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => { |
| 24 | if (err) { |
| 25 | FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, err); |
| 26 | } |
| 27 | }); |
| 28 | } |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | private open(filePath: string): void { |
| 33 | try { |
| 34 | fs.openSync(filePath, 'w+'); |
| 35 | } catch (error) { |
| 36 | FileUtils.handleFileException(this.logPrefix, 'Performance measurements', filePath, error); |
| 37 | } |
| 38 | } |
| 39 | } |