-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrequest.js
134 lines (117 loc) · 3.17 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import fetch from 'isomorphic-unfetch'
import dns from './dns'
const DEVICE_TYPE = 'WEB'
const authorizationKey = 'AUTHORIZATION'
export const testApiRoot = async rootUrl => {
const response = await fetch(`${rootUrl}/ping`)
const { ok, status } = response
if (ok && status === 200) {
const text = await response.text()
if (text === 'pong') {
return rootUrl
}
return Promise.reject()
}
return Promise.reject(new Error(`ok: ${ok}, status: ${status}`))
}
export const setApiRoot = async newApiRoot => {
dns.API_ROOT = newApiRoot
localStorage.setItem('API_ROOT', newApiRoot)
return newApiRoot
}
export const getApiRootByRacing = async () => {
try {
const newApiRoot = await Promise.race(dns.REMOTE_HOSTS.map(testApiRoot))
return setApiRoot(newApiRoot)
} catch (error) {
const msg = `Failed to ping any remote: ${error}`
return Promise.reject(new Error(msg))
}
}
export const getApiRoot = async () => {
if (localStorage.getItem('resolveByLocal') === 'true') {
return setApiRoot(dns.API_ROOT_LOCAL)
}
// return getApiRootByRacing()
return setApiRoot(dns.API_ROOT_REMOTE)
}
export const getAuthorization = () => {
return localStorage.getItem(authorizationKey)
}
export const setAuthorization = s => {
localStorage.setItem(authorizationKey, s)
}
const guestTokenKey = 'GUEST_TOKEN'
export const guestToken = () => {
if (!process.browser) return null
let token = localStorage.getItem(guestTokenKey)
if (!token) {
token = 'GUEST'.concat(
Math.random()
.toString(36)
.substring(7)
)
localStorage.setItem(guestTokenKey, token)
}
return token
}
export const getJwtToken = () => {
const authorization = getAuthorization()
if (authorization) {
return authorization.split(' ')[1]
}
return guestToken()
}
export const removeAuthorization = () => {
localStorage.removeItem(authorizationKey)
}
const headers = () => {
return {
Authorization: getAuthorization(),
Accept: 'application/json',
'Content-Type': 'application/json'
}
}
const body = data => {
return {
DEVICE_TYPE,
...data
}
}
const parseResponse = async res => {
if (res.headers.get('Authorization')) {
setAuthorization(res.headers.get('Authorization'))
}
const json = await res.json()
if (res.status >= 400) {
json.status = res.status
}
if (res.status === 401) {
removeAuthorization()
}
return json
}
export const get = async (path, data = {}, _token = '') => {
const params = body(data)
const query = Object.keys(params)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
.join('&')
const res = await fetch(`${dns.API_ROOT}/${path}?${query}`, {
method: 'GET',
headers: headers(_token)
})
const content = await parseResponse(res)
return content
}
const requestMethod = method => async (path, data, _token = '') => {
const res = await fetch(`${dns.API_ROOT}/${path}`, {
method,
headers: headers(_token),
body: JSON.stringify(body(data))
})
const content = await parseResponse(res)
return content
}
export const post = requestMethod('POST')
export const put = requestMethod('PUT')
export const httpDelete = requestMethod('DELETE')