Skip to content

Instantly share code, notes, and snippets.

@iethree
Last active August 4, 2022 14:03
Show Gist options
  • Save iethree/570ef46a1eba643073229e9249ebddfe to your computer and use it in GitHub Desktop.
Save iethree/570ef46a1eba643073229e9249ebddfe to your computer and use it in GitHub Desktop.
fetchWithTimeout
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');
});
}
@andrevenancio
Copy link

FetchError is not used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment