[Utils] Implement timeout for safeFetch (#62)
* implement timeout for safeFetch * update typedef --------- Co-authored-by: Beef <beefers@riseup.net>
This commit is contained in:
parent
b271240f76
commit
ef0b162d3a
2 changed files with 15 additions and 5 deletions
|
@ -1,7 +1,17 @@
|
|||
// A really basic fetch wrapper which throws on non-ok response codes
|
||||
|
||||
export default async function safeFetch(input: RequestInfo | URL, options?: RequestInit) {
|
||||
const req = await fetch(input, options);
|
||||
export default async function safeFetch(input: RequestInfo | URL, options?: RequestInit, timeout = 10000) {
|
||||
const req = await fetch(input, {
|
||||
signal: timeoutSignal(timeout),
|
||||
...options
|
||||
});
|
||||
|
||||
if (!req.ok) throw new Error("Request returned non-ok");
|
||||
return req;
|
||||
}
|
||||
}
|
||||
|
||||
function timeoutSignal(ms: number): AbortSignal {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(`Timed out after ${ms}ms`), ms);
|
||||
return controller.signal;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue