I am using a vue + nuxt.js application, I like to know if it is possible to cache an axios webservice call for all clients. I have to get some currency reference data and this makes not much sense that every client has to call this data.
Can someone provide me some hints or even an example? Thx.
Here is working solution with latest Nuxt 2.11, using locally defined module.
First add a local module to nuxt.config.js
modules: [
"@/modules/axCache",
...
]
Then
// modules/axCache.js
import LRU from "lru-cache"
export default function(_moduleOptions) {
const ONE_HOUR = 1000 * 60 * 60
const axCache = new LRU({ maxAge: ONE_HOUR })
this.nuxt.hook("vue-renderer:ssr:prepareContext", ssrContext => {
ssrContext.$axCache = axCache
})
}
and
// plugins/axios.js
import { cacheAdapterEnhancer } from "axios-extensions"
import LRU from "lru-cache"
const ONE_HOUR = 1000 * 60 * 60
export default function({ $axios, ssrContext }) {
const defaultCache = process.server
? ssrContext.$axCache
: new LRU({ maxAge: ONE_HOUR })
const defaults = $axios.defaults
// https://github.com/kuitos/axios-extensions
defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
enabledByDefault: false,
cacheFlag: "useCache",
defaultCache
})
}
Note, this works for both server/client sides and can be configured to work only on one side.
solution found on: https://github.com/nuxt-community/axios-module/issues/99
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With