Last active
September 19, 2020 18:18
-
-
Save homerjam/933336f19ff1302e7a8dd2c6784dd172 to your computer and use it in GitHub Desktop.
Simple plugin which decorates the community axios nuxt-module with an lru-cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hash from 'object-hash'; | |
import sizeof from 'object-sizeof'; | |
import lruCache from 'lru-cache'; | |
const cacheEnabled = true; | |
const cacheMaxAge = 30 * 60 * 1000; | |
const cacheMaxSize = 128 * 1000 * 1000; | |
const getCacheKey = config => hash({ | |
method: config.method, | |
url: config.url, | |
params: config.params, | |
data: config.data, | |
}); | |
export default async ({ app }) => { | |
const axios = app.$axios; | |
if (!cacheEnabled) { | |
return; | |
} | |
const cache = lruCache({ | |
maxAge: cacheMaxAge, | |
max: cacheMaxSize, | |
length: item => sizeof(item), | |
}); | |
axios.interceptors.request.use((request) => { | |
if (request.method === 'get' && cacheEnabled) { | |
const key = getCacheKey(request); | |
if (cache.has(key)) { | |
const data = cache.get(key); | |
request.data = data; | |
// Set the request adapter to send the cached response | |
// and prevent the request from actually running | |
request.adapter = () => Promise.resolve({ | |
data, | |
status: request.status, | |
statusText: request.statusText, | |
headers: request.headers, | |
config: request, | |
request, | |
}); | |
} | |
} | |
return request; | |
}, error => Promise.reject(error)); | |
axios.interceptors.response.use((response) => { | |
let bypassCache = false; | |
try { | |
// eslint-disable-next-line | |
bypassCache = JSON.parse(response.config.params.__cache) === false; | |
} catch (error) { | |
// | |
} | |
if (cacheEnabled && !bypassCache && response.config.method === 'get') { | |
const key = getCacheKey(response.config); | |
cache.set(key, response.data); | |
} | |
return response; | |
}, error => Promise.reject(error)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment