forked from Yadro/time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFileRepository.ts
More file actions
61 lines (50 loc) · 1.73 KB
/
AbstractFileRepository.ts
File metadata and controls
61 lines (50 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const fs = require('fs');
const path = require('path');
import FsHelper from '../../helpers/FsHelper';
import PromiseQueue from '../../helpers/PromiseQueueHellper';
const APP_DIR = 'YadroTimeTracker';
export default abstract class AbstractFileRepository<T = any> {
dirWithProfileData: string = 'profile1';
fileName: string = 'defaultFileName.json';
saveInRoot: boolean = false;
writeFileQueue = new PromiseQueue();
private get logPrefix() {
const filePath = !this.saveInRoot ? this.dirWithProfileData : '';
return `FileRepository [${filePath}/${this.fileName}]:`;
}
private static get appDataFolder() {
return process.env.APPDATA || '';
}
private get destFolder() {
const pathItems = [AbstractFileRepository.appDataFolder, APP_DIR];
if (!this.saveInRoot) {
pathItems.push(this.dirWithProfileData);
}
return path.join(...pathItems);
}
private get filePath() {
return path.join(this.destFolder, this.fileName);
}
public setProfile(profile: string) {
this.dirWithProfileData = profile;
}
public restore(defaultValue: T): T {
console.log(`${this.logPrefix} restore`);
if (fs.existsSync(this.filePath)) {
const data = fs.readFileSync(this.filePath, { encoding: 'utf-8' });
// TODO handle parse error. Backup file with issues and return defaultValue
return JSON.parse(data);
}
return defaultValue;
}
public save(data: T) {
FsHelper.mkdirIfNotExists(this.destFolder);
this.writeFileQueue.add(() => {
console.log(`${this.logPrefix} save`);
return FsHelper.writeFile(this.filePath, data).catch(() => {
console.error(`${this.logPrefix} can't save file '${this.filePath}'`);
});
});
this.writeFileQueue.execute();
}
}