From ef0b162d3a1e55651c26442a1f68c2c9bdf4df55 Mon Sep 17 00:00:00 2001 From: Amsyar Rasyiq <82711525+amsyarasyiq@users.noreply.github.com> Date: Sat, 15 Apr 2023 23:25:03 +0800 Subject: [PATCH] [Utils] Implement timeout for safeFetch (#62) * implement timeout for safeFetch * update typedef --------- Co-authored-by: Beef --- src/def.d.ts | 4 ++-- src/lib/utils/safeFetch.ts | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/def.d.ts b/src/def.d.ts index 3c59945..ec8becc 100644 --- a/src/def.d.ts +++ b/src/def.d.ts @@ -342,7 +342,7 @@ interface LoaderIdentity { } interface DiscordStyleSheet { - [index: string]: any, + [index: string]: any, createThemedStyleSheet: typeof import("react-native").StyleSheet.create; } @@ -402,7 +402,7 @@ interface VendettaObject { utils: { findInReactTree: (tree: SearchTree, filter: SearchFilter) => any; findInTree: (tree: SearchTree, filter: SearchFilter, options: FindInTreeOptions) => any; - safeFetch: (input: RequestInfo | URL, options?: RequestInit) => Promise; + safeFetch: (input: RequestInfo | URL, options?: RequestInit, timeout?: number) => Promise; unfreeze: (obj: object) => object; without: (object: O, ...keys: K) => Omit; }; diff --git a/src/lib/utils/safeFetch.ts b/src/lib/utils/safeFetch.ts index 1c743de..a4f7685 100644 --- a/src/lib/utils/safeFetch.ts +++ b/src/lib/utils/safeFetch.ts @@ -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; -} \ No newline at end of file +} + +function timeoutSignal(ms: number): AbortSignal { + const controller = new AbortController(); + setTimeout(() => controller.abort(`Timed out after ${ms}ms`), ms); + return controller.signal; +}