-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathRequest.js
77 lines (71 loc) · 1.47 KB
/
Request.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
const METHOD={
GET:'GET',
POST:'POST',
PUT:'PUT',
DELETE:'DELETE'
}
class Request{
_header={
token:null
}
_baseUrl=null
interceptors = []
constructor(){
const token=wx.getStorageSync('token')
if(token){
this._header.token=token
}
}
intercept(res){
return this.interceptors
.filter(f=> typeof f === 'function')
.every(f=> f(res))
}
request({url,method,header={},data}){
return new Promise((resolve,reject)=>{
wx.request({
url: (this._baseUrl || '')+url,
method: method || METHOD.GET,
data: data,
header: {
...this._header,
...header
},
success: res=>this.intercept(res) && resolve(res),
fail:reject
})
})
}
get(url,data,header){
return this.request({url,method:METHOD.GET,header,data})
}
post(url,data,header){
return this.request({url,method:METHOD.POST,header,data})
}
put(url,data,header){
return this.request({url,method:METHOD.PUT,header,data})
}
delete(url,data,header){
return this.request({url,method:METHOD.DELETE,header,data})
}
token(token){
this._header.token=token
return this
}
header(header){
this._header=header
return this
}
baseUrl(baseUrl){
this._baseUrl=baseUrl
return this
}
interceptor(f){
if(typeof f === 'function'){
this.interceptors.push(f)
}
return this
}
}
export default new Request
export {METHOD}