@itwin/core-frontend
Version:
iTwin.js frontend components
64 lines • 2.32 kB
JavaScript
;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpResponseError = void 0;
exports.request = request;
/** Error object that's thrown if the status is *not* in the range of 200-299 (inclusive).
* @internal
*/
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;
}
}
exports.HttpResponseError = HttpResponseError;
/** @internal */
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