Skip to content

Instantly share code, notes, and snippets.

@Tuarisa
Last active October 3, 2021 21:28
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Tuarisa/b7c07289eb32b2a7a77be270e1c8360f to your computer and use it in GitHub Desktop.
Save Tuarisa/b7c07289eb32b2a7a77be270e1c8360f to your computer and use it in GitHub Desktop.
Nuxt axios cache plugin
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 = obj => hash(obj)
const getCacheKeyObjRequest = config => {
return {
method: config.method,
url: config.baseURL + (config.url ? config.url : ''),
params: config.params,
data: config.data
}
}
const getCacheKeyObjResponse = config => {
return {
method: config.method,
url: config.url,
params: config.params,
data: config.data
}
}
const cache = lruCache({
maxAge: cacheMaxAge,
max: cacheMaxSize,
length: item => sizeof(item)
})
export default async ({ app }) => {
const axios = app.$axios
if (!cacheEnabled) {
return
}
axios.interceptors.request.use((request) => {
if (request.method === 'get' && cacheEnabled) {
const key = getCacheKey(getCacheKeyObjRequest(request))
if (cache.has(key)) {
const {data, headers} = 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: 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(getCacheKeyObjResponse(response.config))
cache.set(key, {data: response.data, headers: response.headers})
}
return response
}, error => Promise.reject(error))
}
@timrijkse
Copy link

thanks man

@cloudinstone
Copy link

how to use it man.

@metinjakupi
Copy link

Did you test this code? you need to update cache function ( need to add new lruCache)
const cache =new lruCache({ maxAge: cacheMaxAge, max: cacheMaxSize, length: item => sizeof(item) })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment