[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
2
src/def.d.ts
vendored
2
src/def.d.ts
vendored
|
@ -402,7 +402,7 @@ interface VendettaObject {
|
||||||
utils: {
|
utils: {
|
||||||
findInReactTree: (tree: SearchTree, filter: SearchFilter) => any;
|
findInReactTree: (tree: SearchTree, filter: SearchFilter) => any;
|
||||||
findInTree: (tree: SearchTree, filter: SearchFilter, options: FindInTreeOptions) => any;
|
findInTree: (tree: SearchTree, filter: SearchFilter, options: FindInTreeOptions) => any;
|
||||||
safeFetch: (input: RequestInfo | URL, options?: RequestInit) => Promise<Response>;
|
safeFetch: (input: RequestInfo | URL, options?: RequestInit, timeout?: number) => Promise<Response>;
|
||||||
unfreeze: (obj: object) => object;
|
unfreeze: (obj: object) => object;
|
||||||
without: <O extends object, K extends readonly (keyof O)[]>(object: O, ...keys: K) => Omit<O, typeof keys[number]>;
|
without: <O extends object, K extends readonly (keyof O)[]>(object: O, ...keys: K) => Omit<O, typeof keys[number]>;
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,7 +1,17 @@
|
||||||
// A really basic fetch wrapper which throws on non-ok response codes
|
// A really basic fetch wrapper which throws on non-ok response codes
|
||||||
|
|
||||||
export default async function safeFetch(input: RequestInfo | URL, options?: RequestInit) {
|
export default async function safeFetch(input: RequestInfo | URL, options?: RequestInit, timeout = 10000) {
|
||||||
const req = await fetch(input, options);
|
const req = await fetch(input, {
|
||||||
|
signal: timeoutSignal(timeout),
|
||||||
|
...options
|
||||||
|
});
|
||||||
|
|
||||||
if (!req.ok) throw new Error("Request returned non-ok");
|
if (!req.ok) throw new Error("Request returned non-ok");
|
||||||
return req;
|
return req;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function timeoutSignal(ms: number): AbortSignal {
|
||||||
|
const controller = new AbortController();
|
||||||
|
setTimeout(() => controller.abort(`Timed out after ${ms}ms`), ms);
|
||||||
|
return controller.signal;
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue