umami/lib/web.js

74 lines
2 KiB
JavaScript
Raw Permalink Normal View History

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