umami/lib/web.js
2020-07-26 00:12:42 -07:00

39 lines
1020 B
JavaScript

export const apiRequest = (method, url, body) =>
fetch(url, {
method,
cache: 'no-cache',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body,
}).then(res => (res.ok ? res.json() : null));
function parseQuery(url, params) {
const query =
params &&
Object.keys(params).reduce((values, key) => {
if (params[key] !== undefined) {
return values.concat(`${key}=${encodeURIComponent(params[key])}`);
}
return values;
}, []);
return query.length ? `${url}?${query.join('&')}` : url;
}
export const get = (url, params) => apiRequest('get', parseQuery(url, params));
export const post = (url, params) => apiRequest('post', url, JSON.stringify(params));
export const del = (url, params) => apiRequest('del', parseQuery(url, params));
export const hook = (_this, method, callback) => {
const orig = _this[method];
return (...args) => {
callback.apply(null, args);
return orig.apply(_this, args);
};
};