2017-12-13 11:01:37 +00:00
|
|
|
/* @flow */
|
2018-07-30 10:52:13 +00:00
|
|
|
|
2017-12-13 11:01:37 +00:00
|
|
|
|
|
|
|
import 'whatwg-fetch';
|
|
|
|
|
|
|
|
export const httpRequest = async (url: string, type: string = 'text'): any => {
|
|
|
|
const response: Response = await fetch(url, { credentials: 'same-origin' });
|
|
|
|
if (response.ok) {
|
|
|
|
if (type === 'json') {
|
|
|
|
const txt: string = await response.text();
|
|
|
|
return JSON.parse(txt);
|
2018-07-30 10:52:13 +00:00
|
|
|
} if (type === 'binary') {
|
2017-12-13 11:01:37 +00:00
|
|
|
return await response.arrayBuffer();
|
|
|
|
}
|
2018-07-30 10:52:13 +00:00
|
|
|
return await response.text();
|
2017-12-13 11:01:37 +00:00
|
|
|
}
|
2018-07-30 10:52:13 +00:00
|
|
|
throw new Error(`${url} ${response.statusText}`);
|
|
|
|
|
2017-12-13 11:01:37 +00:00
|
|
|
|
|
|
|
// return fetch(url, { credentials: 'same-origin' }).then((response) => {
|
|
|
|
// if (response.status === 200) {
|
|
|
|
|
|
|
|
// return response.text().then(result => (json ? JSON.parse(result) : result));
|
|
|
|
// } else {
|
|
|
|
// throw new Error(response.statusText);
|
|
|
|
// }
|
|
|
|
// })
|
2018-04-16 21:19:50 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const JSONRequest = async (url: string): Promise<JSON> => {
|
|
|
|
const response: Response = await fetch(url, { credentials: 'same-origin' });
|
|
|
|
if (response.ok) {
|
|
|
|
const txt: string = await response.text();
|
|
|
|
return JSON.parse(txt);
|
|
|
|
}
|
2018-07-30 10:52:13 +00:00
|
|
|
throw new Error(`jsonRequest error: ${response.toString()}`);
|
2017-12-13 11:01:37 +00:00
|
|
|
};
|