-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapters.ts
51 lines (40 loc) · 1.33 KB
/
adapters.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
import { createError } from './errors'
import { AxiosRequestConfig, AxiosResponse } from './typding'
import { buildUrl, transformRequestData } from './helpers'
export const adapterXHR = (config: AxiosRequestConfig) => {
return new Promise<AxiosResponse>((resolve, reject) => {
const request = new XMLHttpRequest()
request.open(config.method.toUpperCase(), buildUrl(config))
Object.keys(config.headers).forEach(k =>
request.setRequestHeader(k, config.headers[k])
)
request.timeout = config.timeout
request.onreadystatechange = () => {
if (request.readyState !== 4) {
return
}
const response: AxiosResponse = {
data:
config.responseType === 'text'
? request.responseText
: request.response,
status: request.status,
headers: config.headers,
config,
request
}
if (request.status && request.status >= 200 && request.status < 300) {
resolve(response)
} else {
reject(createError(request.status, 'Request failed', request, response))
}
}
request.onerror = () => {
console.error(request)
reject(createError(null, 'Network Error', request))
}
request.onabort = () => {}
request.ontimeout = () => {}
request.send((config.data as any) || null)
})
}