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

Commit 7a9e015

Browse files
committed
Async saving files
1 parent d6e3ca5 commit 7a9e015

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed
Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
const fs = require('fs');
22
const path = require('path');
33

4+
import FsHelper from '../../helpers/FsHelper';
5+
46
const APP_FOLDER = 'YadroTimeTracker';
57
const PROFILE_FOLDER = 'profile1';
68

@@ -16,7 +18,7 @@ export default abstract class AbstractFileRepository<T = any> {
1618
return path.join(
1719
AbstractFileRepository.appDataFolder,
1820
APP_FOLDER,
19-
PROFILE_FOLDER
21+
PROFILE_FOLDER,
2022
);
2123
}
2224

@@ -27,22 +29,14 @@ export default abstract class AbstractFileRepository<T = any> {
2729
public restore(defaultValue: T): T {
2830
if (fs.existsSync(this.filePath)) {
2931
const data = fs.readFileSync(this.filePath);
32+
// TODO handle parse error. Backup file with issues and return defaultValue
3033
return JSON.parse(data);
3134
}
3235
return defaultValue;
3336
}
3437

3538
public save(data: T) {
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);
46-
}
39+
FsHelper.mkdirIfNotExists(AbstractFileRepository.profileFolder);
40+
return FsHelper.writeFile(this.filePath, data);
4741
}
4842
}

src/helpers/FsHelper.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const fs = require('fs');
2+
3+
const FsHelper = {
4+
writeFile(path: string, data: any) {
5+
return new Promise<void>((resolve, reject) => {
6+
fs.writeFile(path, JSON.stringify(data), 'utf-8', (err: NodeJS.ErrnoException | null) => {
7+
if (err) {
8+
reject(err);
9+
} else {
10+
resolve();
11+
}
12+
});
13+
})
14+
},
15+
mkdirIfNotExists(path: string) {
16+
if (!fs.existsSync(path)) {
17+
fs.mkdirSync(path, { recursive: true });
18+
}
19+
},
20+
};
21+
22+
export default FsHelper;

0 commit comments

Comments
 (0)