-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.js
58 lines (45 loc) · 1.11 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
import to from './to'
const JWT_TOKEN = 'TESTE';
const getHeaders = () => {
const jwtToken = localStorage.getItem(JWT_TOKEN)
const Authorization = jwtToken ? `${jwtToken}` : ''
return new Headers({
Authorization,
'Content-Type': 'application/json',
Accept: 'application/json',
// 'X-Requested-With': 'XMLHttpRequest',
})
}
const resolveFetch = (res) => {
const json = res.json()
if (!res.ok) {
throw json
}
return json
}
const getConfig = (config, payload) =>
payload ? { ...config, ...{ body: JSON.stringify(payload) } } : config
export const request = async (
url,
method,
payload,
) => {
const config = {
method,
headers: getHeaders(),
// credentials: 'same-origin',
}
const [results, err] = await to(
fetch(url, getConfig(config, payload)).then(resolveFetch),
)
if (err) {
throw err
}
return results
}
export const get = (url) => request(url, 'GET')
export const post = (url, payload) =>
request(url, 'POST', payload)
export const put = (url, payload) =>
request(url, 'PUT', payload)
export const destroy = (url) => request(url, 'DELETE')