index.ts
2.5 KB
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
import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { HYRequestConfig } from './types'
import EventBus from '@/utils/events'
// import router from "../../router"
/**
* 两个难点:
* 1. 拦截器进行精细控制
* > 全局拦截器
* > 实例拦截器
* > 单次请求拦截器
* 2. 响应结果的类型处理(泛型)
*/
class HYRequest {
instance: AxiosInstance
// request 实例 => axios 实例
constructor(config: HYRequestConfig) {
this.instance = axios.create(config)
// 每个 instance 实例都添加拦截器
this.instance.interceptors.request.use((config) => {
// loading/token
return config
}, err => {
console.log('全局请求失败的拦截', err)
return err
})
this.instance.interceptors.response.use(res => {
// console.log('全局相应成功的拦截')
return res.data
}, err => {
if (err.response.data.code === 401) {
EventBus.emit('notLogin', err.response.data.message)
}
console.log('全局相应失败的拦截', err.response.data)
return err
})
// 针对特定的 hyRequest 实例添加拦截器
if (config.interceptors) {
this.instance.interceptors.request.use(
config?.interceptors.requestSuccessFn,
config?.interceptors.requestFailureFn
)
this.instance.interceptors.response.use(
config?.interceptors.responseSuccessFn,
config?.interceptors.responseFailureFn
)
}
}
request<T = any>(config: HYRequestConfig<T>) {
// 单次请求的成功拦截器
if (config.interceptors?.requestSuccessFn) {
config = config.interceptors.requestSuccessFn(config)
}
return new Promise<T>((resolve, reject) => {
this.instance.request<any, T>(config).then(res => {
// 单词响应的成功拦截器
if (config.interceptors?.responseSuccessFn) {
res = config.interceptors.responseSuccessFn(res)
}
resolve(res)
}).catch(err => {
reject(err)
})
})
}
get<T = any>(config: HYRequestConfig<T>) {
return this.request({ ...config, method: "GET" })
}
post<T = any>(config: HYRequestConfig<T>) {
return this.request({ ...config, method: "POST" })
}
delete<T = any>(config: HYRequestConfig<T>) {
return this.request({ ...config, method: "DELETE" })
}
patch<T = any>(config: HYRequestConfig<T>) {
return this.request({ ...config, method: "PATCH" })
}
}
export default HYRequest