From 6ac23c6054b78532743e971ab31a64f7a384f980 Mon Sep 17 00:00:00 2001 From: kwaroran Date: Mon, 25 Mar 2024 18:58:05 +0900 Subject: [PATCH] Refactor globalFetch function to simplify and improve readability --- src/ts/storage/globalApi.ts | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/ts/storage/globalApi.ts b/src/ts/storage/globalApi.ts index d256df69..28ec54d9 100644 --- a/src/ts/storage/globalApi.ts +++ b/src/ts/storage/globalApi.ts @@ -551,20 +551,21 @@ export async function globalFetch(url: string, arg: GlobalFetchArgs = {}): Promi const urlHost = new URL(url).hostname const forcePlainFetch = (knownHostes.includes(urlHost) && !isTauri) || db.usePlainFetch || arg.plainFetchForce - if (knownHostes.includes(urlHost) && !isTauri && !isNodeServer) - return { ok: false, headers: {}, data: 'You are trying local request on web version. This is not allowed due to browser security policy. Use the desktop version instead, or use a tunneling service like ngrok and set the CORS to allow all.' } + if (knownHostes.includes(urlHost) && !isTauri && !isNodeServer){ + return { ok: false, headers: {}, data: 'You are trying local request on web version. This is not allowed due to browser security policy. Use the desktop version instead, or use a tunneling service like ngrok and set the CORS to allow all.' } + } // Simplify the globalFetch function: Detach built-in functions - if (forcePlainFetch) { + if (forcePlainFetch) { return await fetchWithPlainFetch(url, arg); - } - if (isTauri) { + } + if (isTauri) { return await fetchWithTauri(url, arg); - } - if (Capacitor.isNativePlatform()) { + } + if (Capacitor.isNativePlatform()) { return await fetchWithCapacitor(url, arg); - } - return await fetchWithProxy(url, arg); + } + return await fetchWithProxy(url, arg); } catch (error) { console.error(error); @@ -602,7 +603,7 @@ function addFetchLogInGlobalFetch(response:any, success:boolean, url:string, arg async function fetchWithPlainFetch(url: string, arg: GlobalFetchArgs): Promise { try { const headers = { 'Content-Type': 'application/json', ...arg.headers }; - const response = await fetch(new URL(url), { body: JSON.stringify(arg.body), headers, method: arg.method, signal: arg.abortSignal }); + const response = await fetch(new URL(url), { body: JSON.stringify(arg.body), headers, method: arg.method ?? "POST", signal: arg.abortSignal }); const data = arg.rawResponse ? new Uint8Array(await response.arrayBuffer()) : await response.json(); const ok = response.ok && response.status >= 200 && response.status < 300; addFetchLogInGlobalFetch(data, ok, url, arg); @@ -618,7 +619,7 @@ async function fetchWithTauri(url: string, arg: GlobalFetchArgs): Promise