UNPKG

@ceramicnetwork/common

Version:
28 lines 1.22 kB
import { mergeAbortSignals, TimedAbortSignal, abortable } from './abort-signal-utils.js'; const DEFAULT_FETCH_TIMEOUT = 60 * 1000 * 3; export async function fetchJson(url, opts = {}) { if (opts.body) { const headers = { 'Content-Type': 'application/json', ...opts.headers }; Object.assign(opts, { body: headers['Content-Type'] == 'application/json' ? JSON.stringify(opts.body) : opts.body, headers: headers, }); } const timeoutLength = opts.timeout || DEFAULT_FETCH_TIMEOUT; const timedAbortSignal = new TimedAbortSignal(timeoutLength); const signal = opts.signal ? mergeAbortSignals([opts.signal, timedAbortSignal.signal]) : timedAbortSignal.signal; const res = await abortable(signal, (abortSignal) => { return fetch(String(url), { ...opts, signal: abortSignal, credentials: 'include' }); }).finally(() => timedAbortSignal.clear()); if (!res.ok) { const text = await res.text(); throw new Error(`HTTP request to '${url}' failed with status '${res.statusText}': ${text}`); } if (res.status === 204) { return {}; } return res.json(); } //# sourceMappingURL=fetch-json.js.map