@@ -6,31 +6,56 @@ import { ICache } from '../interfaces/cache';
66import storageService , { StorageService } from './storage' ;
77
88export class CacheService {
9+ private change$ = new rxjs . Subject < { key : string , value : ICache } > ( ) ;
910 private memory : { [ key : string ] : ICache } ;
1011
1112 constructor ( private storageService : StorageService ) {
1213 this . memory = { } ;
1314 }
1415
15- public getData ( key : string ) : rxjs . Observable < ICache > {
16+ public getData < T = any > ( key : string ) : rxjs . Observable < ICache < T > > {
1617 if ( this . memory [ key ] ) return rxjs . of ( this . memory [ key ] ) ;
1718 return this . storageService . get ( 'app-cache-' + key ) ;
1819 }
1920
20- public saveData < T > ( key : string , data : T , options : { persist : boolean , expirationMinutes : number } ) : rxjs . Observable < ICache < T > > {
21+ public watchData < T > ( key : string ) : rxjs . Observable < ICache < T > > {
22+ return this . getData < T > ( key ) . pipe (
23+ rxjsOperators . concat ( this . change$ . pipe (
24+ rxjsOperators . filter ( data => data . key === key ) ,
25+ rxjsOperators . map ( data => data . value )
26+ ) ) ,
27+ rxjsOperators . debounceTime ( 100 )
28+ ) ;
29+ }
30+
31+ public removeData ( key : string ) {
32+ return this . storageService . set ( 'app-cache-' + key , null ) . pipe (
33+ rxjsOperators . tap ( ( ) => this . memory [ key ] = null ) ,
34+ rxjsOperators . tap ( ( ) => this . change$ . next ( { key, value : null } ) )
35+ ) ;
36+ }
37+
38+ public saveData < T > (
39+ key : string ,
40+ data : T ,
41+ options : { persist : boolean , expirationMinutes : number } = { persist : false , expirationMinutes : 5 }
42+ ) : rxjs . Observable < ICache < T > > {
2143 const cache : ICache < T > = {
2244 createdAt : new Date ( ) ,
2345 expirationDate : DateTime . local ( ) . plus ( { minutes : options . expirationMinutes } ) . toJSDate ( ) ,
2446 data
2547 } ;
2648
2749 if ( options . persist ) {
28- return this . storageService . set ( 'app-cache-' + key , cache ) ;
50+ return this . storageService . set ( 'app-cache-' + key , cache ) . pipe (
51+ rxjsOperators . tap ( ( ) => this . change$ . next ( { key, value : cache } ) )
52+ ) ;
2953 }
3054
3155 return rxjs . of ( true ) . pipe (
3256 rxjsOperators . map ( ( ) => {
3357 this . memory [ key ] = cache ;
58+ this . change$ . next ( { key, value : cache } ) ;
3459 return cache ;
3560 } )
3661 ) ;
@@ -46,7 +71,9 @@ export class CacheService {
4671 }
4772
4873 public clear ( ) : rxjs . Observable < void > {
49- return this . storageService . clear ( / ^ a p p - c a c h e - / gi) ;
74+ return this . storageService . clear ( / ^ a p p - c a c h e - / gi) . pipe (
75+ rxjsOperators . tap ( ( ) => this . memory = { } )
76+ ) ;
5077 }
5178
5279}
0 commit comments