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'; | |
c63c21bc | 8 | import lockfile from 'proper-lockfile'; |
72f041bd JB |
9 | |
10 | export class JSONFileStorage extends Storage { | |
2a370053 JB |
11 | private fd: number | null = null; |
12 | ||
72f041bd JB |
13 | constructor(storageURI: string, logPrefix: string) { |
14 | super(storageURI, logPrefix); | |
a6b3c6c3 | 15 | this.dbName = this.storageURI.pathname; |
72f041bd JB |
16 | } |
17 | ||
18 | public storePerformanceStatistics(performanceStatistics: Statistics): void { | |
2a370053 | 19 | this.checkPerformanceRecordsFile(); |
c63c21bc JB |
20 | lockfile.lock(this.dbName, { stale: 5000, retries: 3 }) |
21 | .then(async (release) => { | |
22 | try { | |
23 | const fileData = fs.readFileSync(this.dbName, 'utf8'); | |
24 | const performanceRecords: Statistics[] = fileData ? JSON.parse(fileData) as Statistics[] : []; | |
25 | performanceRecords.push(performanceStatistics); | |
26 | fs.writeFileSync(this.dbName, JSON.stringify(performanceRecords, null, 2), 'utf8'); | |
27 | } catch (error) { | |
28 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); | |
29 | } | |
30 | await release(); | |
31 | }) | |
32 | .catch(() => { }); | |
72f041bd | 33 | } |
b652b0c3 | 34 | |
2a370053 | 35 | public open(): void { |
b652b0c3 | 36 | try { |
a6ceb16a JB |
37 | if (!this?.fd) { |
38 | this.fd = fs.openSync(this.dbName, 'a+'); | |
39 | } | |
b652b0c3 | 40 | } catch (error) { |
2a370053 JB |
41 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); |
42 | } | |
43 | } | |
44 | ||
45 | public close(): void { | |
46 | try { | |
a6ceb16a | 47 | if (this?.fd) { |
2a370053 JB |
48 | fs.closeSync(this.fd); |
49 | this.fd = null; | |
50 | } | |
51 | } catch (error) { | |
52 | FileUtils.handleFileException(this.logPrefix, Constants.PERFORMANCE_RECORDS_FILETYPE, this.dbName, error); | |
53 | } | |
54 | } | |
55 | ||
56 | private checkPerformanceRecordsFile(): void { | |
73d09045 | 57 | if (!this?.fd) { |
2a370053 | 58 | throw new Error(`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`); |
b652b0c3 JB |
59 | } |
60 | } | |
72f041bd | 61 | } |