2018-02-11 18:49:32 +00:00
|
|
|
const TIMEOUT = 15000
|
|
|
|
|
2018-02-11 22:11:03 +00:00
|
|
|
function fetchWithTimeout (url, options) {
|
2018-02-24 02:23:36 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
fetch(url, options).then(resolve, reject)
|
|
|
|
setTimeout(() => reject(new Error(`Timed out after ${TIMEOUT / 1000} seconds`)), TIMEOUT)
|
|
|
|
})
|
2018-02-11 18:49:32 +00:00
|
|
|
}
|
|
|
|
|
2018-02-24 02:23:36 +00:00
|
|
|
async function _post (url, body, headers, timeout) {
|
|
|
|
let fetchFunc = timeout ? fetchWithTimeout : fetch
|
|
|
|
return (await fetchFunc(url, {
|
2018-01-13 22:19:51 +00:00
|
|
|
method: 'POST',
|
2018-02-24 02:23:36 +00:00
|
|
|
headers: Object.assign(headers, {
|
2018-01-13 22:19:51 +00:00
|
|
|
'Accept': 'application/json',
|
|
|
|
'Content-Type': 'application/json'
|
2018-02-24 02:23:36 +00:00
|
|
|
}),
|
2018-01-13 22:19:51 +00:00
|
|
|
body: JSON.stringify(body)
|
|
|
|
})).json()
|
|
|
|
}
|
|
|
|
|
2018-02-24 02:23:36 +00:00
|
|
|
async function _get (url, headers, timeout) {
|
|
|
|
let fetchFunc = timeout ? fetchWithTimeout : fetch
|
|
|
|
return (await fetchFunc(url, {
|
2018-01-13 22:19:51 +00:00
|
|
|
method: 'GET',
|
|
|
|
headers: Object.assign(headers, {
|
2018-02-09 06:29:29 +00:00
|
|
|
'Accept': 'application/json'
|
2018-01-13 22:19:51 +00:00
|
|
|
})
|
|
|
|
})).json()
|
2018-02-09 06:29:29 +00:00
|
|
|
}
|
2018-02-24 02:23:36 +00:00
|
|
|
|
|
|
|
export async function post (url, body, headers = {}) {
|
|
|
|
return _post(url, body, headers, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function postWithTimeout (url, body, headers = {}) {
|
|
|
|
return _post(url, body, headers, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getWithTimeout (url, headers = {}) {
|
|
|
|
return _get(url, headers, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function get (url, headers = {}) {
|
|
|
|
return _get(url, headers, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function paramsString (paramsObject) {
|
|
|
|
let params = new URLSearchParams()
|
|
|
|
Object.keys(paramsObject).forEach(key => {
|
|
|
|
params.set(key, paramsObject[key])
|
|
|
|
})
|
|
|
|
return params.toString()
|
|
|
|
}
|