Skip to content

Instantly share code, notes, and snippets.

@bovas85
Last active September 16, 2023 12:46
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bovas85/8b5610ac94dd036628f53f702b300a64 to your computer and use it in GitHub Desktop.
Save bovas85/8b5610ac94dd036628f53f702b300a64 to your computer and use it in GitHub Desktop.
NuxtServerInit caching mechanism
import { cacheAdapterEnhancer } from 'axios-extensions'
import LRUCache from 'lru-cache'
const ONE_HOUR = 1000 * 60 * 60
const defaultCache = new LRUCache({ maxAge: ONE_HOUR })
export default function ({ $axios }) {
const defaults = $axios.defaults
// https://github.com/kuitos/axios-extensions
defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
enabledByDefault: false,
cacheFlag: 'useCache',
defaultCache
})
}
const Config = require('./assets/config')
const axios = require('axios')
module.exports = {
... // other config
/*
** Generate dynamic pages configuration
*/
generate: {
routes: function () {
return axios.get(`${Config.wpDomain}${Config.api.projects}`).then(res => {
return res.data.map(project => {
return { route: '/' + project.slug, payload: project }
})
})
}
},
plugins: [
'~/plugins/axios.js',
// ...other plugins here
]
... // other config
}
import Vuex from 'vuex'
import Config from '~/assets/config.js'
const createStore = () => {
return new Vuex.Store({
state: {
homePage: []
},
mutations: {
setHomepage (state, obj) {
state.homePage = obj
}
},
actions: {
async nuxtServerInit ({ commit }, { app, route }) {
console.log('============= Server Init API calls =============')
try {
console.log('home')
const home = await app.$axios.get(
Config.wpDomain + Config.api.homePage,
{ useCache: true }
)
commit('setHomepage', home.data)
} catch (e) {
console.log('error with API', e)
}
}
}
})
}
export default createStore
@davodaslanifakor
Copy link

How can set dynamic maxAge for each request ?

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