Last active
August 4, 2022 14:03
-
-
Save iethree/570ef46a1eba643073229e9249ebddfe to your computer and use it in GitHub Desktop.
fetchWithTimeout
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
import fetch from 'node-fetch'; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export type ObjectWithStringKeys = { [key: string]: any }; | |
export function fetchWithTimeout(url: string, options: ObjectWithStringKeys = {}) { | |
const controller = new AbortController(); | |
const timeout = setTimeout(() => { | |
controller.abort(); | |
}, options?.timeout || 7000); | |
return fetch(url, { | |
...options, | |
signal: controller.signal, | |
}).then((res) => { | |
clearTimeout(timeout); | |
return res; | |
}).catch((err: Error) => { | |
clearTimeout(timeout); | |
if (err.name === 'AbortError') { | |
throw new Error('request timed out'); | |
} | |
throw new Error(err.message || 'error fetching'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FetchError
is not used