-
Notifications
You must be signed in to change notification settings - Fork 125
/
MinRequest.js
114 lines (99 loc) · 2.56 KB
/
MinRequest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')
import { checkLogin, checkResult } from '@/utils/checkResponse'
class MinRequest {
[config] = {
baseURL: '',
header: {
'content-type': 'application/json'
},
method: 'GET',
dataType: 'json',
responseType: 'text'
}
interceptors = {
request: (func) => {
if (func) {
MinRequest[requestBefore] = func
} else {
MinRequest[requestBefore] = (request) => request
}
},
response: (func) => {
if (func) {
MinRequest[requestAfter] = func
} else {
MinRequest[requestAfter] = (response) => response
}
}
}
static[requestBefore](config) {
return config
}
static[requestAfter](response) {
return response
}
static[isCompleteURL](url) {
return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}
setConfig(func) {
this[config] = func(this[config])
}
request(options = {}) {
options.baseURL = options.baseURL || this[config].baseURL
options.dataType = options.dataType || this[config].dataType
options.url = MinRequest[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
options.data = options.data
options.header = { ...options.header,
...this[config].header
}
options.method = options.method || this[config].method
options = { ...options,
...MinRequest[requestBefore](options)
}
return new Promise((resolve, reject) => {
options.success = function(res) {
resolve(MinRequest[requestAfter](res))
}
options.fail = function(err) {
reject(MinRequest[requestAfter](err))
}
uni.request(options)
})
}
get(url, data, options = {}) {
options.url = url
options.data = data
options.method = 'GET'
return this.request(options).then(checkLogin).then(checkResult)
}
post(url, data, options = {}) {
options.url = url
options.data = data
options.method = 'POST'
return this.request(options).then(checkLogin).then(checkResult)
}
delete(url, data, options = {}) {
options.url = url
options.data = data
options.method = 'DELETE'
return this.request(options).then(checkLogin).then(checkResult)
}
}
MinRequest.install = function(Vue) {
Vue.mixin({
beforeCreate: function() {
if (this.$options.minApi) {
Vue._minApi = this.$options.minApi
}
}
})
Object.defineProperty(Vue.prototype, '$minApi', {
get: function() {
return Vue._minApi.apis
}
})
}
export default MinRequest