UNPKG

@puls-atlas/cli

Version:

The Puls Atlas CLI tool for managing Atlas projects

48 lines 1.69 kB
import { normalizeOptionalString } from '../../../utils/value.js'; const DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS = 5_000; const createTimeoutSignal = timeoutMs => ({ cleanup: () => {}, signal: AbortSignal.timeout(timeoutMs) }); const normalizeTimeoutError = (error, timeoutMs) => { if (['TimeoutError', 'AbortError'].includes(error?.name)) { return new Error(`request timed out after ${timeoutMs}ms`); } return error; }; const getRequestFailureDetail = error => { const causeMessage = normalizeOptionalString(error?.cause?.message); if (causeMessage) { return causeMessage; } const errorMessage = normalizeOptionalString(error?.message); if (errorMessage && errorMessage !== 'fetch failed') { return errorMessage; } return 'the remote endpoint could not be reached from this machine'; }; const normalizeRequestError = (error, url, timeoutMs) => { const normalizedError = normalizeTimeoutError(error, timeoutMs); if (normalizedError?.message?.startsWith('request timed out after')) { return new Error(`${normalizedError.message} while requesting ${url}`); } return new Error(`request failed for ${url}: ${getRequestFailureDetail(normalizedError)}`); }; export const fetchWithTimeout = async (url, options = {}, timeoutMs = DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS, dependencies = {}) => { const fetchImpl = dependencies.fetchImpl ?? fetch; const { cleanup, signal } = createTimeoutSignal(timeoutMs); try { return await fetchImpl(url, { ...options, signal }); } catch (error) { throw normalizeRequestError(error, url, timeoutMs); } finally { cleanup(); } }; export { DEFAULT_PROVIDER_REQUEST_TIMEOUT_MS };