-
Notifications
You must be signed in to change notification settings - Fork 0
/
axios.ts
61 lines (50 loc) · 1.57 KB
/
axios.ts
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
import { defaults } from './configs'
import { AxiosError, AxiosRequestConfig, AxiosResponse } from './typding'
import { margeConfig, transformRequestData, transformResponse } from './helpers'
import { InterceptorManager } from './interceptor'
class Axios {
interceptors = {
request: new InterceptorManager<AxiosRequestConfig>(),
response: new InterceptorManager<AxiosError>()
}
constructor(public config: AxiosRequestConfig) {}
request<T = any>(config: Partial<AxiosRequestConfig>) {
let _config = margeConfig(config, this.config)
const adapter = _config.adapter
if (_config.data) {
_config.data = transformRequestData(
_config.data,
_config.headers,
_config.transformRequestData
)
}
this.interceptors.request.forEach(({ onFulfilled, onRejected }) => {
try {
_config = onFulfilled(_config)
} catch (e) {
onRejected(e)
return false
}
})
const onAdapterResolved = (response: AxiosResponse<T>) => {
return transformResponse(response, _config.transformResponse)
}
const onAdapterRejected = (reason: AxiosError) => {
// TODO Transform response
return Promise.reject(reason)
}
let promise: Promise<AxiosResponse<T>>
promise = adapter(_config).then(onAdapterResolved, onAdapterRejected)
return promise
}
}
/**
* create custom instance
*/
export function createAxios(config?: Partial<AxiosRequestConfig>) {
return new Axios(margeConfig(config || {}))
}
/**
* axios build-in instance
*/
export const axios = createAxios(defaults)