-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathfetch.ts
More file actions
21 lines (18 loc) · 808 Bytes
/
fetch.ts
File metadata and controls
21 lines (18 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Server-only wrapper around `fetch` that applies an AbortSignal timeout.
// Bare fetch has no timeout — a slow upstream (BCMR, Cauldron, CryptoCompare)
// blocks a Node worker until the peer eventually gives up (minutes). Under
// concurrency that starves the event loop.
export interface TimedFetchInit extends RequestInit {
timeoutMs?: number;
}
const DEFAULT_TIMEOUT_MS = 5000;
export async function timedFetch(
url: string | URL,
init: TimedFetchInit = {}
): Promise<Response> {
const { timeoutMs = DEFAULT_TIMEOUT_MS, signal, ...rest } = init;
const timeoutSignal = AbortSignal.timeout(timeoutMs);
// If the caller passed its own signal, combine both.
const combined = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
return fetch(url, { ...rest, signal: combined });
}