Last active
November 15, 2022 16:14
-
-
Save imaginamundo/88f54c97bb154044350ad831aaf4eb30 to your computer and use it in GitHub Desktop.
A wrapper for fetch with timeout using abort controller and a specific timeout error with url and status.
This file contains 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
const DEFAULT_TIMEOUT = 3000; | |
function request(resource, options = {}) { | |
const { timeout = DEFAULT_TIMEOUT } = options; | |
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) }); | |
} | |
export default request; |
This file contains 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
interface RequestOptions extends RequestInit { | |
timeout?: number; | |
} | |
const DEFAULT_TIMEOUT = 3000; | |
function request( | |
resource: string | Request | URL, | |
options: RequestOptions | undefined = {} | |
): Promise<Response> { | |
const { timeout = DEFAULT_TIMEOUT } = options; | |
delete options.timeout; | |
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) }); | |
} | |
export default request; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment