|
1 | 1 | const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | + |
| 4 | +const APP_FOLDER = 'YadroTimeTracker'; |
| 5 | +const PROFILE_FOLDER = 'profile1'; |
2 | 6 |
|
3 | 7 | export default abstract class AbstractFileRepository<T = any> { |
4 | | - folder: string = 'profile1'; |
| 8 | + folderWithProfile: string = 'profile1'; |
5 | 9 | fileName: string = 'defaultFileName.json'; |
6 | 10 |
|
7 | | - get path() { |
8 | | - return `${this.folder}/${this.fileName}`; |
| 11 | + private static get appDataFolder() { |
| 12 | + return process.env.APPDATA || ''; |
| 13 | + } |
| 14 | + |
| 15 | + private static get profileFolder() { |
| 16 | + return path.join( |
| 17 | + AbstractFileRepository.appDataFolder, |
| 18 | + APP_FOLDER, |
| 19 | + PROFILE_FOLDER |
| 20 | + ); |
| 21 | + } |
| 22 | + |
| 23 | + private get filePath() { |
| 24 | + return path.join(AbstractFileRepository.profileFolder, this.fileName); |
9 | 25 | } |
10 | 26 |
|
11 | 27 | public restore(defaultValue: T): T { |
12 | | - if (fs.existsSync(this.path)) { |
13 | | - const data = fs.readFileSync(this.path); |
| 28 | + if (fs.existsSync(this.filePath)) { |
| 29 | + const data = fs.readFileSync(this.filePath); |
14 | 30 | return JSON.parse(data); |
15 | 31 | } |
16 | 32 | return defaultValue; |
17 | 33 | } |
18 | 34 |
|
19 | 35 | public save(data: T) { |
20 | | - if (!fs.existsSync(this.folder)) { |
21 | | - fs.mkdirSync(this.folder); |
| 36 | + [ |
| 37 | + path.join(AbstractFileRepository.appDataFolder, APP_FOLDER), |
| 38 | + AbstractFileRepository.profileFolder, |
| 39 | + ].forEach((p) => AbstractFileRepository.createFolderIfNotExists(p)); |
| 40 | + fs.writeFileSync(this.filePath, JSON.stringify(data), 'utf-8'); |
| 41 | + } |
| 42 | + |
| 43 | + private static createFolderIfNotExists(path: string) { |
| 44 | + if (!fs.existsSync(path)) { |
| 45 | + fs.mkdirSync(path); |
22 | 46 | } |
23 | | - fs.writeFileSync(this.path, JSON.stringify(data), 'utf-8'); |
24 | 47 | } |
25 | 48 | } |
0 commit comments