From 2a50814721575f196ccbf39c3220e77b9be1dfb6 Mon Sep 17 00:00:00 2001 From: Beef Date: Sat, 4 Feb 2023 16:54:03 +0000 Subject: [PATCH] [Utils > safeFetch] Implement --- src/lib/plugins.ts | 5 +++-- src/lib/utils/safeFetch.ts | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 src/lib/utils/safeFetch.ts diff --git a/src/lib/plugins.ts b/src/lib/plugins.ts index 99bb7cb..06620ed 100644 --- a/src/lib/plugins.ts +++ b/src/lib/plugins.ts @@ -1,6 +1,7 @@ import { Indexable, PluginManifest, Plugin } from "@types"; import { navigation } from "@metro/common"; import { awaitSyncWrapper, createStorage, wrapSync } from "@lib/storage"; +import safeFetch from "@utils/safeFetch"; import logger from "@lib/logger"; import Subpage from "@ui/settings/components/Subpage"; @@ -22,7 +23,7 @@ export async function fetchPlugin(id: string, enabled = true) { let pluginManifest: PluginManifest; try { - pluginManifest = await (await fetch(id + "manifest.json", { cache: "no-store" })).json(); + pluginManifest = await (await safeFetch(id + "manifest.json", { cache: "no-store" })).json(); } catch { throw new Error(`Failed to fetch manifest for ${id}`); } @@ -32,7 +33,7 @@ export async function fetchPlugin(id: string, enabled = true) { // TODO: Remove duplicate error if possible try { // by polymanifest spec, plugins should always specify their main file, but just in case - pluginJs = await (await fetch(id + (pluginManifest.main || "index.js"), { cache: "no-store" })).text(); + pluginJs = await (await safeFetch(id + (pluginManifest.main || "index.js"), { cache: "no-store" })).text(); } catch { throw new Error(`Failed to fetch JS for ${id}`); } diff --git a/src/lib/utils/safeFetch.ts b/src/lib/utils/safeFetch.ts new file mode 100644 index 0000000..652e517 --- /dev/null +++ b/src/lib/utils/safeFetch.ts @@ -0,0 +1,7 @@ +// A really basic fetch wrapper which throws on non-ok response codes + +export default async function safeFetch(input: RequestInfo, options?: RequestInit) { + const req = await fetch(input, options); + if (!req.ok) throw new Error("Request returned non-ok"); + return req; +} \ No newline at end of file