umami/lib/web.js

66 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-09-26 07:31:18 +02:00
import { getQueryString } from './url';
2020-10-01 00:14:44 +02:00
export const apiRequest = (method, url, body, headers) =>
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',
2020-09-23 03:35:11 +02:00
credentials: 'same-origin',
2020-07-24 04:56:55 +02:00
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
2020-10-01 00:14:44 +02:00
...headers,
2020-07-24 04:56:55 +02:00
},
2020-07-26 09:12:42 +02:00
body,
}).then(res => {
if (res.ok) {
2020-10-01 00:14:44 +02:00
return res.json().then(data => ({ ok: res.ok, status: res.status, data }));
}
2020-08-09 11:03:37 +02:00
2020-10-01 00:14:44 +02:00
return res.text().then(data => ({ ok: res.ok, status: res.status, res: res, data }));
});
2020-07-26 09:12:42 +02:00
2020-09-26 07:31:18 +02:00
export const get = (url, params) => apiRequest('get', `${url}${getQueryString(params)}`);
2020-07-26 09:12:42 +02:00
2020-09-26 07:31:18 +02:00
export const del = (url, params) => apiRequest('delete', `${url}${getQueryString(params)}`);
2020-07-26 09:12:42 +02:00
export const post = (url, params) => apiRequest('post', url, JSON.stringify(params));
export const put = (url, params) => apiRequest('put', url, JSON.stringify(params));
export const hook = (_this, method, callback) => {
const orig = _this[method];
return (...args) => {
callback.apply(null, args);
return orig.apply(_this, args);
};
};
2020-08-21 11:51:42 +02:00
export const doNotTrack = () => {
2020-08-23 22:34:00 +02:00
const { doNotTrack, navigator, external } = window;
const msTracking = () => {
return (
external &&
typeof external.msTrackingProtectionEnabled === 'function' &&
external.msTrackingProtectionEnabled()
);
};
const dnt = doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || msTracking();
return dnt === true || dnt === 1 || dnt === 'yes' || dnt === '1';
2020-08-22 12:03:39 +02:00
};
export const setItem = (key, data, session) => {
if (typeof window !== 'undefined') {
(session ? sessionStorage : localStorage).setItem(key, JSON.stringify(data));
}
};
export const getItem = (key, session) =>
typeof window !== 'undefined'
? JSON.parse((session ? sessionStorage : localStorage).getItem(key))
: null;