This repository has been archived by the owner on Dec 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
32 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters