Skip to content

Instantly share code, notes, and snippets.

@kenberkeley
Last active July 21, 2020 04:12
Show Gist options
  • Save kenberkeley/5397109922ad10f6e40e9a0b7f1d2048 to your computer and use it in GitHub Desktop.
Save kenberkeley/5397109922ad10f6e40e9a0b7f1d2048 to your computer and use it in GitHub Desktop.
Nuxt.js: Ajax with client cache
import axios from 'axios'
import hashSum from 'hash-sum' // for key gen
import clone from 'fast-copy' // for cutting the reference
/**
* Nuxt.js: request with client cache (imitate Google search association results)
* @param {Object} req
* @param {string} [req.method='get']
* @param {string} req.url
* @param {Object} [req.data]
* @param {boolean} [req.noCache]
* @return {Promise<any>}
*/
const cache = {}
export default function (req) {
if (process.server || req.noCache) {
return request(req)
}
const hash = hashSum(req)
if (cache[hash]) {
return Promise.resolve(clone(cache[hash]))
}
return request(req).then(resData => {
cache[hash] = clone(resData)
return resData
})
}
function request ({ method = 'get', url, data }) {
return new Promise((resolve, reject) => {
axios({ method, url, data }).then(res => {
// https://github.com/axios/axios#response-schema
if (res.status === 200) {
resolve(res.data)
return
}
// deal with error
}).catch(err => {
// https://github.com/axios/axios#handling-errors
// deal with error
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment