2020-07-26 09:12:42 +02:00
|
|
|
export const apiRequest = (method, url, body) =>
|
2020-07-24 04:56:55 +02:00
|
|
|
fetch(url, {
|
2020-07-26 09:12:42 +02:00
|
|
|
method,
|
2020-07-24 04:56:55 +02:00
|
|
|
cache: 'no-cache',
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/json',
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
2020-07-26 09:12:42 +02:00
|
|
|
body,
|
2020-07-28 10:17:45 +02:00
|
|
|
}).then(res => {
|
|
|
|
if (res.ok) {
|
|
|
|
return res.json();
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
});
|
2020-07-26 09:12:42 +02:00
|
|
|
|
2020-07-28 10:17:45 +02:00
|
|
|
function parseQuery(url, params = {}) {
|
|
|
|
const query = Object.keys(params).reduce((values, key) => {
|
|
|
|
if (params[key] !== undefined) {
|
|
|
|
return values.concat(`${key}=${encodeURIComponent(params[key])}`);
|
|
|
|
}
|
|
|
|
return values;
|
|
|
|
}, []);
|
2020-07-26 09:12:42 +02:00
|
|
|
return query.length ? `${url}?${query.join('&')}` : url;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const get = (url, params) => apiRequest('get', parseQuery(url, params));
|
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
export const del = (url, params) => apiRequest('delete', parseQuery(url, params));
|
|
|
|
|
2020-07-26 09:12:42 +02:00
|
|
|
export const post = (url, params) => apiRequest('post', url, JSON.stringify(params));
|
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
export const put = (url, params) => apiRequest('put', url, JSON.stringify(params));
|
2020-07-24 07:07:57 +02:00
|
|
|
|
|
|
|
export const hook = (_this, method, callback) => {
|
|
|
|
const orig = _this[method];
|
|
|
|
|
|
|
|
return (...args) => {
|
|
|
|
callback.apply(null, args);
|
|
|
|
|
|
|
|
return orig.apply(_this, args);
|
|
|
|
};
|
|
|
|
};
|