UNPKG

1.67 kBJavaScriptView Raw
1/*
2 * @Filename: index.js
3 * @Author: jin5354
4 * @Email: xiaoyanjinx@gmail.com
5 * @Last Modified time: 2017-06-23 16:50:54
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 return Promise.resolve(cacher.getCache(option))
34 }else {
35 return func(...arg).then(response => {
36 cacher.setCache(option, response)
37 return response
38 })
39 }
40 }else {
41 return instance(...arg)
42 }
43 }
44
45 axiosWithCache.get = function(...arg) {
46 if(arg.length === 1) {
47 return requestWithCacheCheck({
48 url: arg[0]
49 }, instance.get, ...arg)
50 }else if(arg.length === 2) {
51 return requestWithCacheCheck({
52 url: arg[0],
53 ...arg[1]
54 }, instance.get, ...arg)
55 }else {
56 return instance.get(...arg)
57 }
58 }
59
60 axiosWithCache.__addFilter = function(filter) {
61 cacher.addFilter(filter)
62 }
63
64 axiosWithCache.__removeFilter = function(filter) {
65 cacher.removeFilter(filter)
66 }
67
68 unCacheMethods.forEach(method => {
69 axiosWithCache[method] = function(...arg) {
70 return instance[method](...arg)
71 }
72 })
73
74 return axiosWithCache
75}