11const threeSecondsOfCache = 3 ;
22const oneSecond = 1000 ;
3+ const cacheControlHeader = "cache-control" ;
4+ const cacheRevalidateHeader = "must-revalidate" ;
35
46export const getCacheKey = ( config ) => {
57 if ( ! config . params ) return `${ config . method } -${ config . url } ` ;
@@ -15,6 +17,16 @@ export const revalidateCache = (key: string) => {
1517 cache . delete ( internalKey ) ;
1618} ;
1719
20+ const getCachedSeconds = ( response : any ) => {
21+ const getSeconds = ( secondsFromMaxAge : string ) =>
22+ secondsFromMaxAge . replace ( "max-age" , "" ) . replace ( "=" , "" ) ;
23+
24+ if ( response . config . headers [ cacheRevalidateHeader ] )
25+ return getSeconds ( response . config . headers [ cacheRevalidateHeader ] ) ;
26+
27+ return getSeconds ( response . config . headers [ cacheControlHeader ] ) ;
28+ } ;
29+
1830type Cache = {
1931 items : Record < string , any > ;
2032 has : ( key : string ) => boolean ;
@@ -55,20 +67,27 @@ export const loadCache = (axios) => {
5567 if ( request . method === "get" ) {
5668 const key = getCacheKey ( request ) ;
5769
58- if ( cache . has ( key ) ) {
59- const { data, headers } = cache . get ( key ) ;
60-
61- request . data = data ;
62-
63- request . adapter = ( ) =>
64- Promise . resolve ( {
65- data,
66- status : request . status ,
67- statusText : request . statusText ,
68- headers,
69- config : request ,
70- request,
71- } ) ;
70+ if ( request . headers [ cacheControlHeader ] ) {
71+ if ( cache . has ( key ) ) {
72+ const { data, headers } = cache . get ( key ) ;
73+
74+ request . data = data ;
75+
76+ request . adapter = ( ) =>
77+ Promise . resolve ( {
78+ data,
79+ status : request . status ,
80+ statusText : request . statusText ,
81+ headers,
82+ config : request ,
83+ request,
84+ } ) ;
85+ } else {
86+ request . headers [ cacheRevalidateHeader ] =
87+ request . headers [ cacheControlHeader ] ;
88+
89+ request . headers [ cacheControlHeader ] = cacheRevalidateHeader ;
90+ }
7291 }
7392 }
7493
@@ -77,12 +96,9 @@ export const loadCache = (axios) => {
7796
7897 axios . interceptors . response . use ( ( response ) => {
7998 if ( response . config . method === "get" ) {
80- if ( ! response . config . headers [ "cache-control" ] ) return response ;
81-
82- const seconds = response . config . headers [ "cache-control" ]
83- . replace ( "max-age" , "" )
84- . replace ( "=" , "" ) ;
99+ if ( ! response . config . headers [ cacheControlHeader ] ) return response ;
85100
101+ const seconds = getCachedSeconds ( response ) ;
86102 const key = getCacheKey ( response . config ) ;
87103 cache . set (
88104 key ,
0 commit comments