[Utils] Implement timeout for safeFetch (#62)

* implement timeout for safeFetch

* update typedef

---------

Co-authored-by: Beef <beefers@riseup.net>
This commit is contained in:
Amsyar Rasyiq 2023-04-15 23:25:03 +08:00 committed by GitHub
parent b271240f76
commit ef0b162d3a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 5 deletions

View file

@ -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;
}