UNPKG

@openpass/openpass-js-sdk

Version:
61 lines 1.85 kB
/** * Executes a fetch request * @param url the url of the request * @param options the options of the request */ export const fetchRequest = async (url, options) => { if (options.timeout) { return await fetchRequestWithTimeout(url, options); } const response = await fetch(url, options); return { status: response.status, json: await parseJsonResponseBody(response), }; }; /** * Execute a fetch request with a timeout * @param url the url of the request * @param options the fetch options */ const fetchRequestWithTimeout = async (url, options) => { let timeoutId; try { const controller = new AbortController(); timeoutId = setTimeout(() => controller.abort(), options.timeout); const response = await fetch(url, { ...options, signal: controller.signal, }); return { status: response.status, json: await parseJsonResponseBody(response), }; } finally { if (timeoutId) { clearTimeout(timeoutId); } } }; export const createFormBody = (bodyObj) => { const formBody = []; Object.keys(bodyObj).forEach((property) => { if (bodyObj[property]) { const encodedKey = encodeURIComponent(property); const encodedValue = encodeURIComponent(bodyObj[property]); formBody.push(encodedKey + "=" + encodedValue); } }); if (formBody.length > 0) { return formBody.join("&"); } return ""; }; const parseJsonResponseBody = async (response) => { var _a; if (!((_a = response.headers.get("content-type")) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes("application/json"))) return null; return await response.json(); }; //# sourceMappingURL=fetch.js.map