-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathindex.js
93 lines (77 loc) · 2.39 KB
/
index.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
// https://github.com/diegohaz/arc/wiki/API-service
import { stringify } from 'query-string'
import merge from 'lodash/merge'
import { apiUrl } from 'config'
export const checkStatus = (response) => {
if (response.ok) {
return response
}
const error = new Error(`${response.status} ${response.statusText}`)
error.response = response
throw error
}
export const parseJSON = (response) => response.json()
export const parseSettings = ({
method = 'get', data, locale, ...otherSettings
} = {}) => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
'Accept-Language': locale,
}
const settings = merge({
body: data ? JSON.stringify(data) : undefined,
method,
headers,
}, otherSettings)
return settings
}
export const parseEndpoint = (endpoint, params) => {
const url = endpoint.indexOf('http') === 0 ? endpoint : apiUrl + endpoint
const querystring = params ? `?${stringify(params)}` : ''
return `${url}${querystring}`
}
const api = {}
api.request = (endpoint, { params, ...settings } = {}) => fetch(parseEndpoint(endpoint, params), parseSettings(settings))
.then(checkStatus)
.then(parseJSON);
['delete', 'get'].forEach((method) => {
api[method] = (endpoint, settings) => api.request(endpoint, { method, ...settings })
});
['post', 'put', 'patch'].forEach((method) => {
api[method] = (endpoint, data, settings) => api.request(endpoint, { method, data, ...settings })
})
api.create = (settings = {}) => ({
settings,
setToken(token) {
this.settings.headers = {
...this.settings.headers,
Authorization: `Bearer ${token}`,
}
},
unsetToken() {
this.settings.headers = {
...this.settings.headers,
Authorization: undefined,
}
},
request(endpoint, settings) {
return api.request(endpoint, merge({}, this.settings, settings))
},
post(endpoint, data, settings) {
return this.request(endpoint, { method: 'post', data, ...settings })
},
get(endpoint, settings) {
return this.request(endpoint, { method: 'get', ...settings })
},
put(endpoint, data, settings) {
return this.request(endpoint, { method: 'put', data, ...settings })
},
patch(endpoint, data, settings) {
return this.request(endpoint, { method: 'patch', data, ...settings })
},
delete(endpoint, settings) {
return this.request(endpoint, { method: 'delete', ...settings })
},
})
export default api