1
1
import { AxiosResponse , InternalAxiosRequestConfig } from 'axios' ;
2
2
import qs from 'qs' ;
3
3
4
+ const defaultTtl : number = 1000 * 60 * 5 ;
5
+
6
+ function log ( ...args : any [ ] ) {
7
+ if ( import . meta. env . DEV ) {
8
+ console . log ( `${ new Date ( ) . toISOString ( ) } ` , ...args ) ;
9
+ }
10
+ }
11
+
12
+ function checkCacheHasExpired (
13
+ timestamp : number ,
14
+ ttl : number = defaultTtl
15
+ ) : boolean {
16
+ return new Date ( ) . getTime ( ) - timestamp >= ttl ;
17
+ }
18
+
19
+ function clearExpiredCache ( ) {
20
+ log ( 'cache - checando caches expirados...' ) ;
21
+ Object . keys ( localStorage )
22
+ . filter ( ( key : string ) => key . startsWith ( 'cache:' ) )
23
+ . forEach ( ( key ) => {
24
+ const data = localStorage . getItem ( key ) ;
25
+ if ( data ) {
26
+ const { timestamp } = JSON . parse ( data ) ;
27
+ if ( checkCacheHasExpired ( timestamp ) ) {
28
+ localStorage . removeItem ( key ) ;
29
+ }
30
+ }
31
+ } ) ;
32
+ }
33
+
4
34
function getCacheRequestData ( config : InternalAxiosRequestConfig < any > ) {
5
35
if (
6
36
config . method === 'get' &&
7
37
config . url &&
8
38
config . headers [ 'x-app-cache' ] === 'true'
9
39
) {
10
- const url = config . url + '?' + qs . stringify ( config . params ) ;
40
+ const url = 'cache:' + config . url + '?' + qs . stringify ( config . params ) ;
11
41
const cache = localStorage . getItem ( url ) ;
12
42
if ( cache ) {
13
43
const { data, timestamp } = JSON . parse ( cache ) ;
14
- const ttl = 1000 * 60 * 5 ; // 5 minutes
15
- if ( new Date ( ) . getTime ( ) - timestamp >= ttl ) {
16
- console . log ( `cache - expirado - ${ url } ` ) ;
44
+ if ( checkCacheHasExpired ( timestamp ) ) {
45
+ log ( `cache - expirado - ${ url } ` ) ;
17
46
localStorage . removeItem ( url ) ;
18
47
} else {
19
- console . log ( `cache - ok - ${ url } ` ) ;
48
+ log ( `cache - ok - ${ url } ` ) ;
20
49
return data ;
21
50
}
22
51
}
@@ -25,7 +54,8 @@ function getCacheRequestData(config: InternalAxiosRequestConfig<any>) {
25
54
}
26
55
27
56
function handleCacheResponse ( resp : AxiosResponse < any , any > ) {
28
- const url = resp . config . url + '?' + qs . stringify ( resp . config . params ) ;
57
+ const url =
58
+ 'cache:' + resp . config . url + '?' + qs . stringify ( resp . config . params ) ;
29
59
if (
30
60
resp . config . method === 'get' &&
31
61
resp . config . url &&
@@ -44,4 +74,6 @@ function handleCacheResponse(resp: AxiosResponse<any, any>) {
44
74
}
45
75
}
46
76
77
+ clearExpiredCache ( ) ;
78
+
47
79
export { handleCacheResponse , getCacheRequestData } ;
0 commit comments