From 6b61e565b5372d241e52d6fa6b6e2ff35cc707a4 Mon Sep 17 00:00:00 2001 From: Nullptrderef Date: Sun, 21 Apr 2024 09:54:28 +0200 Subject: check for non-2xx, cache any 2xx responses that pass minimal validation --- .../src/pages/home/AddingProviderScreen/index.ts | 41 ++++++++++++++-------- 1 file changed, 26 insertions(+), 15 deletions(-) (limited to 'packages') diff --git a/packages/anastasis-webui/src/pages/home/AddingProviderScreen/index.ts b/packages/anastasis-webui/src/pages/home/AddingProviderScreen/index.ts index 5f49f39e8..365d2e8e7 100644 --- a/packages/anastasis-webui/src/pages/home/AddingProviderScreen/index.ts +++ b/packages/anastasis-webui/src/pages/home/AddingProviderScreen/index.ts @@ -65,27 +65,37 @@ const map: StateViewMap = { export default compose("AddingProviderScreen", useComponentState, map); +const providerResponseCache = new Map(); // `any` is the return type of res.json() export async function testProvider( url: string, expectedMethodType?: string, ): Promise { try { // TODO: look into using core.getProviderInfo :) - const json = await fetch(new URL("config", url).href) - .catch((error) => { - console.error("Provider HTTP Error:", error); - throw new Error( - "Encountered a fatal error whilst testing the provider: " + url, - ); - }) - .then((response) => - response.json().catch((error) => { - console.error("Provider Parsing Error:", error); - throw new Error( - "Encountered a fatal error whilst testing the provider: " + url, - ); - }), - ); + const providerHasUrl = providerResponseCache.has(url); + const json = providerHasUrl + ? providerResponseCache.get(url) + : await fetch(new URL("config", url).href) + .catch((error) => { + console.error("Provider HTTP Error:", error); + throw new Error( + "Encountered a fatal error whilst testing the provider: " + url, + ); + }) + .then(async (response) => { + if (!response.ok) + throw new Error( + `The server ${response.url} responded with a non-2xx response.`, + ); + try { + return await response.json(); + } catch (error) { + console.error("Provider Parsing Error:", error); + throw new Error( + "Encountered a fatal error whilst testing the provider: " + url, + ); + } + }); if (typeof json !== "object") throw new Error( "Encountered a fatal error whilst testing the provider: " + @@ -102,6 +112,7 @@ export async function testProvider( "This provider doesn't have authentication method. Please check the provider's URL and ensure it is properly configured.", ); } + if (!providerHasUrl) providerResponseCache.set(url, json); if (!expectedMethodType) { return; } -- cgit v1.2.3