-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeRequest.js
More file actions
86 lines (73 loc) · 2.01 KB
/
Copy pathmakeRequest.js
File metadata and controls
86 lines (73 loc) · 2.01 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
import check from 'check-arg-types'
import map from '@wasmuth/map'
const toType = check.prototype.toType
let storage = null
let apiUrl = 'http://10.0.2.2:8000'
export const configure = ({ storage: uStorage, apiUrl: uApiUrl }) => {
if (uStorage) storage = uStorage
if (uApiUrl) apiUrl = uApiUrl
}
const safelyParse = (json, key) => {
try {
const parsed = JSON.parse(json)
// console.log('safelyParse', parsed)
return key != null ? parsed[key] : parsed
} catch (_) {
return json
}
}
export const getAuthHeader = (headers = {}) => {
const token = storage != null
? storage.getItem('token')
: null
if (token) {
headers.Authorization = `Token ${token}`
}
return headers
}
const makeErr = (code, msg) => {
const e = new Error(msg)
e.code = code
if (code === 401) {
storage && storage.removeItem('token')
}
console.error('makeErr', { code, msg })
return e
}
export default function makeRequest ({
endpoint,
url,
method = 'get',
data,
headers,
noAuth = false
}) {
if (endpoint != null && endpoint.indexOf('http') === -1) {
url = `${apiUrl}/${endpoint}`
}
if (url == null) {
url = endpoint
}
const xhr = new window.XMLHttpRequest()
const promise = new Promise((resolve, reject) => {
xhr.open(method.toUpperCase(), url)
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return
const badResponse = xhr.status !== 204 && xhr.response === ''
badResponse || xhr.status >= 400
? reject(makeErr(xhr.status, safelyParse(xhr.response, 'detail')))
: resolve(safelyParse(xhr.response))
}
xhr.onerror = () => reject(xhr)
xhr.setRequestHeader('Content-Type', 'application/json')
headers = !noAuth ? getAuthHeader(headers) : {}
if (headers && toType(headers) === 'object') {
map((k, v) => xhr.setRequestHeader(k, v), headers)
}
const dataType = toType(data)
xhr.send(dataType === 'object' || dataType === 'array'
? JSON.stringify(data)
: data)
})
return { xhr, promise }
}