yoho-plugin-cache.js 910 Bytes
import axios from 'axios';
import settle from 'axios/lib/core/settle';
import cache from 'util/cache';
import crypto from 'util/crypto';

export default {
    defaultAdapter: axios.defaults.adapter,
    install() {
        axios.defaults.adapter = config => {
            if (config.cache) {
                config.id = crypto.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;
            });
        };
    }
};