1
1
/* eslint-disable-next-line boundaries/element-types */
2
2
import { SubscribableStore } from './subscribable' ;
3
3
4
+ type StoreDataWithOptionalFields < StoreData > = {
5
+ [ Property in keyof StoreData ] : StoreData [ Property ] | undefined
6
+ } ;
7
+
4
8
export class PersistantStore < StoreData extends Record < string , unknown > > extends SubscribableStore < StoreData > {
5
9
/**
6
10
* Keys of the StoreData type
@@ -11,7 +15,7 @@ export class PersistantStore<StoreData extends Record<string, unknown>> extends
11
15
/**
12
16
* Proxy for data stored
13
17
*/
14
- protected data : StoreData ;
18
+ protected data : StoreDataWithOptionalFields < StoreData > ;
15
19
16
20
/**
17
21
* Storage that would retain information when proxy is cleared
@@ -21,20 +25,29 @@ export class PersistantStore<StoreData extends Record<string, unknown>> extends
21
25
constructor ( keysStored : string [ ] ) {
22
26
super ( ) ;
23
27
this . keysStored = keysStored ;
24
- this . data = new Proxy < StoreData > ( { } as StoreData , this . _data ) ;
28
+ this . data = new Proxy < StoreDataWithOptionalFields < StoreData > > ( { } as StoreDataWithOptionalFields < StoreData > , this . _data ) ;
25
29
26
30
/**
27
31
* Load data from local store to proxy
28
32
*/
29
33
this . loadInitialData ( ) ;
30
34
} ;
31
35
32
- protected get _data ( ) : ProxyHandler < StoreData > {
36
+ protected get _data ( ) : ProxyHandler < StoreDataWithOptionalFields < StoreData > > {
33
37
return {
34
38
get : ( target , prop ) => {
35
39
const item = this . storage . getItem ( prop as string ) ;
36
40
37
- return item !== null ? JSON . parse ( item ) : undefined ;
41
+ try {
42
+ return item !== null ? JSON . parse ( item ) : undefined ;
43
+ } catch {
44
+ console . warn ( `Persistant store: Cannot parse ${ item } ` ) ;
45
+
46
+ /**
47
+ * Delete item that cannot be parsed
48
+ */
49
+ this . storage . removeItem ( prop as string ) ;
50
+ }
38
51
} ,
39
52
40
53
set : ( target , prop , value , receiver ) => {
@@ -74,7 +87,16 @@ export class PersistantStore<StoreData extends Record<string, unknown>> extends
74
87
const storedValue = this . storage . getItem ( key ) ;
75
88
76
89
if ( storedValue !== null ) {
77
- this . data [ key as keyof StoreData ] = JSON . parse ( storedValue ) ;
90
+ try {
91
+ this . data [ key as keyof StoreData ] = JSON . parse ( storedValue ) ;
92
+ } catch {
93
+ console . warn ( `Persistant store: Cannot parse ${ storedValue } ` ) ;
94
+
95
+ /**
96
+ * Delete item that cannot be parsed
97
+ */
98
+ this . storage . removeItem ( key ) ;
99
+ }
78
100
}
79
101
}
80
102
}
0 commit comments