1
1
import mitt , { Emitter } from "mitt" ;
2
2
3
- import lsAdapter from "./ls -adapter" ;
4
- import { FlagName , FlagValue } from "./types" ;
3
+ import localStorageAdapter from "./local-storage -adapter" ;
4
+ import { FlagName , FlagValue , FLAG_NAMES } from "./types" ;
5
5
6
- type Events = { change : string } ;
6
+ type Events = {
7
+ change : string ;
8
+ } ;
7
9
8
10
/**
9
11
* In memory key value storage.
10
12
*
11
- * Can potentially be backed by localStorage if present
13
+ * Can potentially be backed by localStorage if present.
12
14
13
- * Emits `change` when a key is set (eventEmitter)
15
+ * Emits `change` when a key is set (eventEmitter).
14
16
*/
15
17
class FlagStore {
16
- longtermStore : typeof lsAdapter | null ;
17
-
18
+ longTermStore : typeof localStorageAdapter | null ;
18
19
store : Record < string , any > ;
19
20
ee : Emitter < Events > ;
20
21
21
22
constructor ( ) {
22
23
this . store = { } ;
23
- this . longtermStore = null ;
24
+ this . longTermStore = null ;
24
25
this . ee = mitt ( ) ;
26
+
25
27
if ( typeof localStorage !== "undefined" ) {
26
- this . longtermStore = lsAdapter ;
28
+ this . longTermStore = localStorageAdapter ;
27
29
}
30
+
28
31
this . restore ( ) ;
29
32
}
30
33
31
34
restore ( ) {
32
- if ( ! this . longtermStore ) {
35
+ const longTermStore = this . longTermStore ;
36
+
37
+ if ( ! longTermStore ) {
33
38
return ;
34
39
}
35
- const allValues = this . longtermStore . getAll ( ) ;
40
+
41
+ const allValues = longTermStore . getAll ( ) ;
42
+
36
43
Object . entries ( allValues ) . forEach ( ( [ flag , val ] ) => {
37
- this . store [ flag ] = val ;
38
- this . ee . emit ( "change" , flag ) ;
44
+ if ( FLAG_NAMES . includes ( flag as FlagName ) ) {
45
+ this . store [ flag ] = val ;
46
+ this . ee . emit ( "change" , flag ) ;
47
+ } else {
48
+ longTermStore . removeItem ( flag ) ;
49
+ }
39
50
} ) ;
40
51
}
41
52
@@ -47,26 +58,29 @@ class FlagStore {
47
58
if ( ! Object . prototype . hasOwnProperty . call ( this . store , name ) ) {
48
59
this . store [ name ] = null ;
49
60
}
61
+
50
62
return this . store [ name ] ;
51
63
}
52
64
53
65
set ( name : FlagName , value : FlagValue ) {
54
- if ( this . longtermStore ) {
55
- this . longtermStore . setItem ( name , value ) ;
66
+ if ( this . longTermStore ) {
67
+ this . longTermStore . setItem ( name , value ) ;
56
68
}
69
+
57
70
this . store [ name ] = value ;
58
71
this . ee . emit ( "change" , name ) ;
59
72
}
60
73
61
74
remove ( name : FlagName ) {
62
75
delete this . store [ name ] ;
63
- if ( this . longtermStore ) {
64
- this . longtermStore . removeItem ( name ) ;
76
+
77
+ if ( this . longTermStore ) {
78
+ this . longTermStore . removeItem ( name ) ;
65
79
}
80
+
66
81
this . ee . emit ( "change" , name ) ;
67
82
}
68
83
69
- // eslint-disable-next-line class-methods-use-this
70
84
removeListener ( _event : string , _fn : ( changed : string ) => void ) { }
71
85
}
72
86
0 commit comments