11import mitt , { Emitter } from "mitt" ;
22
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" ;
55
6- type Events = { change : string } ;
6+ type Events = {
7+ change : string ;
8+ } ;
79
810/**
911 * In memory key value storage.
1012 *
11- * Can potentially be backed by localStorage if present
13+ * Can potentially be backed by localStorage if present.
1214
13- * Emits `change` when a key is set (eventEmitter)
15+ * Emits `change` when a key is set (eventEmitter).
1416 */
1517class FlagStore {
16- longtermStore : typeof lsAdapter | null ;
17-
18+ longTermStore : typeof localStorageAdapter | null ;
1819 store : Record < string , any > ;
1920 ee : Emitter < Events > ;
2021
2122 constructor ( ) {
2223 this . store = { } ;
23- this . longtermStore = null ;
24+ this . longTermStore = null ;
2425 this . ee = mitt ( ) ;
26+
2527 if ( typeof localStorage !== "undefined" ) {
26- this . longtermStore = lsAdapter ;
28+ this . longTermStore = localStorageAdapter ;
2729 }
30+
2831 this . restore ( ) ;
2932 }
3033
3134 restore ( ) {
32- if ( ! this . longtermStore ) {
35+ const longTermStore = this . longTermStore ;
36+
37+ if ( ! longTermStore ) {
3338 return ;
3439 }
35- const allValues = this . longtermStore . getAll ( ) ;
40+
41+ const allValues = longTermStore . getAll ( ) ;
42+
3643 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+ }
3950 } ) ;
4051 }
4152
@@ -47,26 +58,29 @@ class FlagStore {
4758 if ( ! Object . prototype . hasOwnProperty . call ( this . store , name ) ) {
4859 this . store [ name ] = null ;
4960 }
61+
5062 return this . store [ name ] ;
5163 }
5264
5365 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 ) ;
5668 }
69+
5770 this . store [ name ] = value ;
5871 this . ee . emit ( "change" , name ) ;
5972 }
6073
6174 remove ( name : FlagName ) {
6275 delete this . store [ name ] ;
63- if ( this . longtermStore ) {
64- this . longtermStore . removeItem ( name ) ;
76+
77+ if ( this . longTermStore ) {
78+ this . longTermStore . removeItem ( name ) ;
6579 }
80+
6681 this . ee . emit ( "change" , name ) ;
6782 }
6883
69- // eslint-disable-next-line class-methods-use-this
7084 removeListener ( _event : string , _fn : ( changed : string ) => void ) { }
7185}
7286
0 commit comments