UNPKG

1.75 kBJavaScriptView Raw
1/*
2 * @Filename: index.js
3 * @Author: jin5354
4 * @Email: xiaoyanjinx@gmail.com
5 * @Last Modified time: 2017-06-23 16:16:09
6 */
7import {Cacher} from './cacher.js'
8
9export default function wrapper(instance, option) {
10
11 const cacher = new Cacher(option)
12
13 const unCacheMethods = [
14 'delete',
15 'head',
16 'options',
17 'post',
18 'put',
19 'patch'
20 ]
21
22 function axiosWithCache(...arg) {
23 if(arg.length === 1 && (arg[0].method === 'get' || arg[0].method === undefined)) {
24 return requestWithCacheCheck(arg[0], instance, ...arg)
25 }else {
26 return instance(...arg)
27 }
28 }
29
30 function requestWithCacheCheck(option, func, ...arg) {
31 if(cacher.needCache(option)) {
32 if(cacher.hasCache(option)) {
33 console.log('命中!')
34 return Promise.resolve(cacher.getCache(option))
35 }else {
36 console.log('未命中,进缓存。')
37 return func(...arg).then(response => {
38 cacher.setCache(option, response)
39 return response
40 })
41 }
42 }else {
43 return instance(...arg)
44 }
45 }
46
47 axiosWithCache.get = function(...arg) {
48 if(arg.length === 1) {
49 return requestWithCacheCheck({
50 url: arg[0]
51 }, instance.get, ...arg)
52 }else if(arg.length === 2) {
53 return requestWithCacheCheck({
54 url: arg[0],
55 ...arg[1]
56 }, instance.get, ...arg)
57 }else {
58 return instance.get(...arg)
59 }
60 }
61
62 axiosWithCache.__addFilter = function(filter) {
63 cacher.addFilter(filter)
64 }
65
66 axiosWithCache.__removeFilter = function(filter) {
67 cacher.removeFilter(filter)
68 }
69
70 unCacheMethods.forEach(method => {
71 axiosWithCache[method] = function(...arg) {
72 return instance[method](...arg)
73 }
74 })
75
76 return axiosWithCache
77}