2019-06-03 03:31:38 +00:00
|
|
|
import config from 'config';
|
|
|
|
|
|
|
|
async function get(endpoint, query = {}) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const curatedQuery = Object.entries(query).reduce((acc, [key, value]) => (value ? { ...acc, [key]: value } : acc), {}); // remove empty values
|
|
|
|
const q = new URLSearchParams(curatedQuery).toString();
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const res = await fetch(`${config.api.url}${endpoint}?${q}`, {
|
|
|
|
method: 'GET',
|
|
|
|
mode: 'cors',
|
|
|
|
credentials: 'same-origin',
|
|
|
|
});
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (res.ok) {
|
|
|
|
return res.json();
|
|
|
|
}
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const errorMsg = await res.text();
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
throw new Error(errorMsg);
|
2019-06-03 03:31:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function post(endpoint, data) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const res = await fetch(`${config.api.url}${endpoint}`, {
|
|
|
|
method: 'POST',
|
|
|
|
mode: 'cors',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
credentials: 'same-origin',
|
|
|
|
body: JSON.stringify(data),
|
|
|
|
});
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (res.ok) {
|
|
|
|
return res.json();
|
|
|
|
}
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const errorMsg = await res.text();
|
2019-06-03 03:31:38 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
throw new Error(errorMsg);
|
2019-06-03 03:31:38 +00:00
|
|
|
}
|
|
|
|
|
2019-12-15 21:16:55 +00:00
|
|
|
async function graphql(query, variables = null) {
|
2020-05-14 02:26:05 +00:00
|
|
|
const res = await fetch('/graphql', {
|
|
|
|
method: 'POST',
|
|
|
|
mode: 'cors',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
credentials: 'same-origin',
|
|
|
|
body: JSON.stringify({
|
|
|
|
query,
|
|
|
|
variables,
|
|
|
|
}),
|
|
|
|
});
|
2019-12-15 04:42:51 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
if (res.ok) {
|
|
|
|
const { data } = await res.json();
|
2019-12-15 04:42:51 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
return data;
|
|
|
|
}
|
2019-12-15 04:42:51 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
const errorMsg = await res.text();
|
2019-12-15 04:42:51 +00:00
|
|
|
|
2020-05-14 02:26:05 +00:00
|
|
|
throw new Error(errorMsg);
|
2019-12-15 04:42:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
2020-05-14 02:26:05 +00:00
|
|
|
get,
|
|
|
|
post,
|
|
|
|
graphql,
|
2019-12-15 04:42:51 +00:00
|
|
|
};
|