Last active
July 21, 2020 04:12
-
-
Save kenberkeley/5397109922ad10f6e40e9a0b7f1d2048 to your computer and use it in GitHub Desktop.
Nuxt.js: Ajax with client cache
This file contains 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 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