UNPKG

@itwin/core-frontend

Version:
59 lines 2.15 kB
/*--------------------------------------------------------------------------------------------- * Copyright (c) Bentley Systems, Incorporated. All rights reserved. * See LICENSE.md in the project root for license terms and full copyright notice. *--------------------------------------------------------------------------------------------*/ /** Error object that's thrown if the status is *not* in the range of 200-299 (inclusive). * @internal */ export class HttpResponseError extends Error { status; responseText; constructor(status, responseText) { let message = `HTTP response status code: ${status}.`; if (responseText) message += ` Response body: ${responseText}`; super(message); this.status = status; this.responseText = responseText; } } /** @internal */ export async function request(url, responseType, options) { const headers = { ...options?.headers, }; if (options?.auth) headers.authorization = `Basic ${window.btoa(`${options.auth.user}:${options.auth.password}`)}`; const controller = new AbortController(); if (options?.timeout) setTimeout(() => controller.abort(), options.timeout); const fetchOptions = { headers, signal: controller.signal, }; const fetchFunc = async () => fetch(url, fetchOptions); const response = await fetchWithRetry(fetchFunc, options?.retryCount ?? 4); if (!response.ok) throw new HttpResponseError(response.status, await response.text()); switch (responseType) { case "arraybuffer": return response.arrayBuffer(); case "json": return response.json(); case "text": return response.text(); } } async function fetchWithRetry(fetchFunc, remainingRetries) { try { return await fetchFunc(); } catch (error) { if (error instanceof Error && error.name === "AbortError") throw error; if (remainingRetries === 0) throw error; return fetchWithRetry(fetchFunc, --remainingRetries); } } //# sourceMappingURL=Request.js.map