1
+ class CacheStore {
2
+ constructor ( cacheKeyPrefix = null ) {
3
+ this . cacheKeyPrefix = cacheKeyPrefix ;
4
+ }
5
+ isNumber ( value ) {
6
+ return ! isNaN ( parseFloat ( value ) ) && ! isNaN ( value - 0 )
7
+ }
8
+ isDate ( value ) {
9
+ return value instanceof Date && ! isNaN ( value . valueOf ( ) )
10
+ }
11
+ put ( key , value , ttl = null ) {
12
+ let createdAt = new Date ( ) ;
13
+ let expiresAt = null ;
14
+
15
+ if ( this . isNumber ( ttl ) ) {
16
+ let date = new Date ( ) ;
17
+ date . setSeconds ( date . getSeconds ( ) + ttl ) ;
18
+ expiresAt = date . toISOString ( ) ;
19
+ }
20
+
21
+ if ( this . isDate ( ttl ) ) {
22
+ expiresAt = ttl . toISOString ( ) ;
23
+ }
24
+
25
+ let cachedData = {
26
+ value, createdAt, expiresAt
27
+ } ;
28
+
29
+ if ( this . cacheKeyPrefix ) {
30
+ key = this . cacheKeyPrefix + key ;
31
+ }
32
+
33
+ localStorage . setItem ( key , JSON . stringify ( cachedData ) ) ;
34
+
35
+ return value ;
36
+ }
37
+ delete ( key ) {
38
+ if ( this . cacheKeyPrefix ) {
39
+ key = this . cacheKeyPrefix + key ;
40
+ }
41
+
42
+ return localStorage . removeItem ( key ) ;
43
+ }
44
+ remember ( key , ttl , callback ) {
45
+ if ( this . cacheKeyPrefix ) {
46
+ key = this . cacheKeyPrefix + key ;
47
+ }
48
+
49
+ let localStorageItem = localStorage . getItem ( key ) ;
50
+
51
+ let cachedData = localStorageItem ? JSON . parse ( localStorageItem ) : undefined ;
52
+
53
+ // If cached data exists and doesn't expire, or if cached data expires, but still hasn't
54
+ if ( cachedData && ( ! cachedData . expiresAt || ( cachedData . expiresAt && cachedData . expiresAt > new Date ( ) . toISOString ( ) ) ) ) {
55
+ return cachedData . value ;
56
+ }
57
+
58
+ this . put ( key , undefined , ttl ) ;
59
+
60
+ let value = callback ( ) ;
61
+
62
+ return this . put ( key , value , ttl ) ;
63
+ }
64
+ rememberForever ( key , callback ) {
65
+ return this . remember ( key , null , callback ) ;
66
+ }
67
+ get ( key , defaultValue = undefined ) {
68
+ if ( this . cacheKeyPrefix ) {
69
+ key = this . cacheKeyPrefix + key ;
70
+ }
71
+
72
+ let localStorageItem = localStorage . getItem ( key ) ;
73
+
74
+ if ( ! localStorageItem ) {
75
+ return defaultValue ;
76
+ }
77
+
78
+ let cachedData = JSON . parse ( localStorageItem ) ;
79
+
80
+ if ( cachedData . expiresAt && cachedData . expiresAt < new Date ( ) . toISOString ( ) ) {
81
+ return defaultValue ;
82
+ }
83
+
84
+ return cachedData . value ;
85
+ }
86
+ }
0 commit comments