import { mergeAbortSignals, TimedAbortSignal, abortable } from './abort-signal-utils.js' const DEFAULT_FETCH_TIMEOUT = 60 * 1000 * 3 // 3 minutes export type FetchOpts = Partial<{ body: any method: HttpMethod headers: any timeout: number signal: AbortSignal }> export type FetchRequestParams = { url: URL | string opts?: FetchOpts } export type FetchRequest = (url: URL | string, opts?: FetchOpts) => Promise export type RFC9110Methods = | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' // Native `fetch` converts lowercase HTTP methods mentioned in RFC9110 to uppercase. // Custom HTTP methods have to be passed as uppercase. So, to be on the safe side, we better uppercase // the method names in our codebase to set an example. export type HttpMethod = RFC9110Methods export async function fetchJson(url: URL | string, opts: Partial = {}): Promise { 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() }