@@ -2,41 +2,60 @@ const fs = require('fs');
22const path = require ( 'path' ) ;
33
44import FsHelper from '../../helpers/FsHelper' ;
5+ import PromiseQueue from '../../helpers/PromiseQueueHellper' ;
56
6- const APP_FOLDER = 'YadroTimeTracker' ;
7- const PROFILE_FOLDER = 'profile1' ;
7+ const APP_DIR = 'YadroTimeTracker_test' ;
88
99export default abstract class AbstractFileRepository < T = any > {
10- folderWithProfile : string = 'profile1' ;
10+ dirWithProfileData : string = 'profile1' ;
1111 fileName : string = 'defaultFileName.json' ;
12+ saveInRoot : boolean = false ;
13+
14+ writeFileQueue = new PromiseQueue ( ) ;
15+
16+ private get logPrefix ( ) {
17+ const filePath = ! this . saveInRoot ? this . dirWithProfileData : '' ;
18+ return `FileRepository [${ filePath } /${ this . fileName } ]:` ;
19+ }
1220
1321 private static get appDataFolder ( ) {
1422 return process . env . APPDATA || '' ;
1523 }
1624
17- private static get profileFolder ( ) {
18- return path . join (
19- AbstractFileRepository . appDataFolder ,
20- APP_FOLDER ,
21- PROFILE_FOLDER ,
22- ) ;
25+ private get destFolder ( ) {
26+ const pathItems = [ AbstractFileRepository . appDataFolder , APP_DIR ] ;
27+ if ( ! this . saveInRoot ) {
28+ pathItems . push ( this . dirWithProfileData ) ;
29+ }
30+ return path . join ( ... pathItems ) ;
2331 }
2432
2533 private get filePath ( ) {
26- return path . join ( AbstractFileRepository . profileFolder , this . fileName ) ;
34+ return path . join ( this . destFolder , this . fileName ) ;
35+ }
36+
37+ public setProfile ( profile : string ) {
38+ this . dirWithProfileData = profile ;
2739 }
2840
2941 public restore ( defaultValue : T ) : T {
42+ console . log ( `${ this . logPrefix } restore` ) ;
3043 if ( fs . existsSync ( this . filePath ) ) {
31- const data = fs . readFileSync ( this . filePath ) ;
44+ const data = fs . readFileSync ( this . filePath , { encoding : 'utf-8' } ) ;
3245 // TODO handle parse error. Backup file with issues and return defaultValue
3346 return JSON . parse ( data ) ;
3447 }
3548 return defaultValue ;
3649 }
3750
3851 public save ( data : T ) {
39- FsHelper . mkdirIfNotExists ( AbstractFileRepository . profileFolder ) ;
40- return FsHelper . writeFile ( this . filePath , data ) ;
52+ FsHelper . mkdirIfNotExists ( this . destFolder ) ;
53+ this . writeFileQueue . add ( ( ) => {
54+ console . log ( `${ this . logPrefix } save` ) ;
55+ return FsHelper . writeFile ( this . filePath , data ) . catch ( ( ) => {
56+ console . error ( `${ this . logPrefix } can't save file '${ this . filePath } '` ) ;
57+ } ) ;
58+ } ) ;
59+ this . writeFileQueue . execute ( ) ;
4160 }
4261}
0 commit comments