yoho-plugin-cache.js
892 Bytes
import axios from 'axios';
import settle from 'axios/lib/core/settle';
import cache from 'cache';
import md5 from 'yoho-md5';
export default {
defaultAdapter: axios.defaults.adapter,
install() {
axios.defaults.adapter = config => {
if (config.cache) {
config.id = md5(`${config.url}|${JSON.stringify(config.params)}|${config.data}`);
let res = cache.get(config.id);
if (res) {
return new Promise(function(resolve, reject) {
settle(resolve, reject, res);
});
}
}
return this.defaultAdapter(config).then(res => {
if (config.cache && res.status === 200 && res.data) {
cache.set(config.id, res);
}
return res;
});
};
}
};