UNPKG

2.03 kBJavaScriptView Raw
1/* eslint-disable */
2
3const { create: createAxios } = require('axios').default;
4const { setupCache } = require('axios-cache-interceptor');
5const { log } = console;
6
7//
8// Complete documentation at:
9// https://axios-cache-interceptor.js.org/
10//
11
12(async () => {
13 const axios = setupCache(
14 // creating axios instance
15 createAxios({ baseURL: 'https://registry.npmjs.org/' }),
16 // configuring the cache
17 { ttl: 99999, interpretHeader: true }
18 );
19
20 const fetchedResponse = await axios.get('/axios-cache-interceptor');
21 // fetchedResponse.cached == false
22
23 //
24 // The next request won't do a network request, because the response is already cached
25 //
26
27 const cachedResponse = await axios.get('/axios-cache-interceptor');
28 // cachedResponse.cached == true
29
30 log(`First request was ${fetchedResponse.cached ? 'cached' : 'fetched'}`);
31 log(`Second request was ${cachedResponse.cached ? 'cached' : 'fetched'}`);
32
33 //
34 // The interpretHeader option used a different strategy, see the received Cache-Control header
35 // (server may return undefined if this is the first request in a while :))
36 //
37
38 log(`Fetched response Cache-Control: ${fetchedResponse.headers['cache-control']}`);
39 log(`Fetched response Age: ${fetchedResponse.headers['age']}`);
40
41 const cacheInformation = await axios.storage.get(fetchedResponse.id);
42
43 //
44 // As you can see, the TTL used was the maxAge cache directive minus the Age header
45 //
46
47 log(`Cache TTL info: ${cacheInformation.ttl}`);
48
49 //
50 // If you disable the interpretHeader option you'll see that the TTL will be the default (99999)\n
51 //
52
53 // Remove the old cache by brute force
54 await axios.storage.remove(fetchedResponse.id);
55
56 const refetchedResponse = await axios.get('/axios-cache-interceptor', {
57 cache: {
58 // This time with interpretHeader disabled
59 interpretHeader: false
60 }
61 });
62
63 const refetchedInformation = await axios.storage.get(refetchedResponse.id);
64
65 log(`Third request TTL: ${refetchedInformation.ttl}`);
66})().catch(console.error);