Last active
December 17, 2023 16:37
-
-
Save jonasgeiler/e175e08515302759c6b0e39e1ab8c581 to your computer and use it in GitHub Desktop.
A simple fetch() wrapper with timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple fetch() wrapper with timeout. | |
* @param input - Same as `fetch()`. | |
* @param init - Same as `fetch()`, but with an extra option `timeout` (defaults to no timeout). | |
* @returns - Same as `fetch()`. | |
*/ | |
export const fetchWithTimeout = (input: RequestInfo, init?: RequestInit & { timeout?: number }) => { | |
if (typeof init?.timeout === 'number') { | |
const controller = new AbortController(); | |
const timeoutId = setTimeout(() => controller.abort(new TimeoutError()), init.timeout); | |
return fetch(input, { | |
signal: controller.signal, | |
...init, | |
}).finally(() => clearTimeout(timeoutId)); | |
} | |
return fetch(input, init); | |
}; | |
/** Custom timeout error for fetchWithTimeout() */ | |
export class TimeoutError extends Error { | |
constructor() { | |
super('Failed to fetch'); | |
this.name = 'TimeoutError'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
signal
ininit
which would override the timeout signal and break stuff (useOmit<>
type)