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

Commit

Permalink
Refactor saving files
Browse files Browse the repository at this point in the history
  • Loading branch information
Yadro committed May 5, 2021
1 parent d5728ad commit 1fcc688
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
39 changes: 31 additions & 8 deletions src/base/repositories/AbstractFileRepository.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
const fs = require('fs');
const path = require('path');

const APP_FOLDER = 'YadroTimeTracker';
const PROFILE_FOLDER = 'profile1';

export default abstract class AbstractFileRepository<T = any> {
folder: string = 'profile1';
folderWithProfile: string = 'profile1';
fileName: string = 'defaultFileName.json';

get path() {
return `${this.folder}/${this.fileName}`;
private static get appDataFolder() {
return process.env.APPDATA || '';
}

private static get profileFolder() {
return path.join(
AbstractFileRepository.appDataFolder,
APP_FOLDER,
PROFILE_FOLDER
);
}

private get filePath() {
return path.join(AbstractFileRepository.profileFolder, this.fileName);
}

public restore(defaultValue: T): T {
if (fs.existsSync(this.path)) {
const data = fs.readFileSync(this.path);
if (fs.existsSync(this.filePath)) {
const data = fs.readFileSync(this.filePath);
return JSON.parse(data);
}
return defaultValue;
}

public save(data: T) {
if (!fs.existsSync(this.folder)) {
fs.mkdirSync(this.folder);
[
path.join(AbstractFileRepository.appDataFolder, APP_FOLDER),
AbstractFileRepository.profileFolder,
].forEach((p) => AbstractFileRepository.createFolderIfNotExists(p));
fs.writeFileSync(this.filePath, JSON.stringify(data), 'utf-8');
}

private static createFolderIfNotExists(path: string) {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
fs.writeFileSync(this.path, JSON.stringify(data), 'utf-8');
}
}
2 changes: 1 addition & 1 deletion src/models/ProjectModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default class ProjectModel extends AbstractModel

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

0 comments on commit 1fcc688

Please sign in to comment.