|
|
const PREFIX = "/api";
function formatUrl(url, params = {}) { const urlWithPrefix = PREFIX + url;
const queryString = Object .keys(params) .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
if (queryString.length > 0) { return urlWithPrefix + "?" + queryString; }
return urlWithPrefix; }
/** * @param {Response} res * @return {Promise<array<object, object>>} */ function authCheck(res) { return res.json().then(json => { if (typeof json.data === "undefined") { json.data = null; }
if (typeof json.error === "undefined") { json.error = null; }
return Promise.resolve(json); }) }
/** * @param {string} url * @param {object} params * @returns {Promise<object|null>} */ export function fetchGet(url, params = {}) { return fetch(formatUrl(url, params), { method: "GET", credentials: "include", }).then(authCheck); }
/** * @param {string} url * @param {object} params * @returns {Promise<object|null>} */ export function fetchDelete(url, params = {}) { return fetch(formatUrl(url, params), { method: "DELETE", credentials: "include", }).then(authCheck); }
/** * @param {string} url * @param {object} data * @returns {Promise<object|null>} */ export function fetchPost(url, data = {}) { return fetch(formatUrl(url), { method: "POST", credentials: "include", headers: { "Content-Type": "application/json; charset=utf-8", }, body: JSON.stringify(data), }).then(authCheck); }
/** * @param {string} url * @param {object} data * @returns {Promise<object|null>} */ export function fetchPatch(url, data = {}) { return fetch(formatUrl(url), { method: "PATCH", credentials: "include", headers: { "Content-Type": "application/json; charset=utf-8", }, body: JSON.stringify(data), }).then(authCheck); }
|