umami/lib/web.js

74 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-10-09 10:04:06 +02:00
import { makeUrl } from './url';
2020-09-26 07:31:18 +02:00
export const apiRequest = (method, url, body, headers) => {
return 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-10-09 08:26:05 +02:00
export const get = (url, params, headers) =>
2020-10-09 10:04:06 +02:00
apiRequest('get', makeUrl(url, params), undefined, headers);
2020-07-26 09:12:42 +02:00
2020-10-09 08:26:05 +02:00
export const del = (url, params, headers) =>
2020-10-09 10:04:06 +02:00
apiRequest('delete', makeUrl(url, params), undefined, headers);
2020-10-09 08:26:05 +02:00
export const post = (url, params, headers) =>
apiRequest('post', url, JSON.stringify(params), headers);
2020-07-26 09:12:42 +02:00
2020-10-09 08:26:05 +02: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 11:51:42 +02:00
export const doNotTrack = () => {
2020-08-23 22:34:00 +02:00
const { doNotTrack, navigator, external } = window;
const msTrackProtection = 'msTrackingProtectionEnabled';
2020-08-23 22:34:00 +02:00
const msTracking = () => {
return external && msTrackProtection in external && external[msTrackProtection]();
2020-08-23 22:34:00 +02:00
};
const dnt = doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || msTracking();
return dnt == '1' || dnt === 'yes';
2020-08-22 12:03:39 +02:00
};
export const setItem = (key, data, session) => {
2022-03-02 07:02:31 +01: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 21:10:47 +01:00
? JSON.parse((session ? sessionStorage : localStorage).getItem(key) || null)
: null;
export const removeItem = (key, session) => {
if (typeof window !== 'undefined') {
(session ? sessionStorage : localStorage).removeItem(key);
}
};