-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
33 lines (27 loc) · 988 Bytes
/
index.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
import 'isomorphic-fetch'
const jsonToQueryString = json => {
let params = []
for (var k in json) params.push(`${k}=${encodeURIComponent(json[k])}`)
return params.join('&')
}
const handleResponseError = response => {
if (response.status >= 400) throw new Error('Bad response from server')
return response.json()
}
const buildJSONHeaders = headers => {
return Object.assign({}, headers, { 'Content-Type': 'application/json' })
}
const postJSON = (uri: RequestInfo, body: object = {}, { headers = {} } = {}) =>
fetch(uri, {
method: 'POST',
body: JSON.stringify(body),
headers: buildJSONHeaders(headers)
}).then(handleResponseError)
const getJSON = (uri: RequestInfo, body?: object, { mode = 'cors' as RequestMode, headers = {} } = {}) => {
const queryString = body ? `?${jsonToQueryString(body)}` : ''
return fetch(`${uri}${queryString}`, {
headers: buildJSONHeaders(headers),
mode
}).then(handleResponseError)
}
export { postJSON, getJSON }