Skip to content
This repository was archived by the owner on Dec 26, 2022. It is now read-only.

Commit 1fcc688

Browse files
committed
Refactor saving files
1 parent d5728ad commit 1fcc688

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed
Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,48 @@
11
const fs = require('fs');
2+
const path = require('path');
3+
4+
const APP_FOLDER = 'YadroTimeTracker';
5+
const PROFILE_FOLDER = 'profile1';
26

37
export default abstract class AbstractFileRepository<T = any> {
4-
folder: string = 'profile1';
8+
folderWithProfile: string = 'profile1';
59
fileName: string = 'defaultFileName.json';
610

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);
925
}
1026

1127
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);
1430
return JSON.parse(data);
1531
}
1632
return defaultValue;
1733
}
1834

1935
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);
2246
}
23-
fs.writeFileSync(this.path, JSON.stringify(data), 'utf-8');
2447
}
2548
}

src/models/ProjectModel.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export default class ProjectModel extends AbstractModel
1818

1919
constructor(props: IJsonProjectItem) {
2020
super();
21-
this.load(props);
21+
this.load(props); // TODO вынести итератор
2222
this.children = props.children?.map((json) => new ProjectModel(json)) || [];
2323
}
2424
}

0 commit comments

Comments
 (0)