From 3f8ca967f1959b5eb840bd038c2de4aff60f3fb0 Mon Sep 17 00:00:00 2001 From: revengeday Date: Sat, 16 Nov 2024 19:45:16 +0000 Subject: [PATCH] Add conditional User-Agent header to API requests - Modified the `apiRequestWithHeaders` function to include a User-Agent header titled "cyber-circle-creator" for outgoing fetch requests. - Implemented retry logic to handle network errors by resending requests without the User-Agent if the initial request fails. --- js/create-circle.js | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/js/create-circle.js b/js/create-circle.js index ae89151..76885b0 100644 --- a/js/create-circle.js +++ b/js/create-circle.js @@ -1,3 +1,8 @@ +/** + * + * @param {RequestInfo | URL} url + * @param {{ body?: any } & RequestInit?} options + */ /** * * @param {RequestInfo | URL} url @@ -6,6 +11,12 @@ async function apiRequestWithHeaders(url, options = null) { console.log(`Fetching :: ${url}`); + // Old version + // ----------------- + // I left the old version in here in case there are any problems. + // The version with user-agent is still very experimental. + + /* if (options && options.body) { options.body = JSON.stringify(options.body); } @@ -26,6 +37,46 @@ async function apiRequestWithHeaders(url, options = null) { error: `Error fetching ${url}: ${error}` }; }); + */ + + // New version with user-agent "cyber-circle-creator" + const defaultUserAgent = { 'User-Agent': 'cyber-circle-creator' }; + + // Merge headers + options = options || {}; + options.headers = { ...(options.headers || {}), ...defaultUserAgent }; + + if (options.body) { + options.body = JSON.stringify(options.body); + } + + try { + const response = await fetch(url, options); + + if (response.ok) { + return { response: { headers: response.headers, body: await response.json(), error: undefined }}; + } + + throw new Error(`Error fetching ${url}: ${response.status} ${response.statusText}`); + } catch (error) { + console.error(`Error fetching with User-Agent "cyber-circle":`, error); + + try { + const fallbackResponse = await fetch(url, { ...(options ?? {}), headers: undefined }); + + if (fallbackResponse.ok) { + return { response: { headers: fallbackResponse.headers, body: await fallbackResponse.json(), error: undefined }}; + } + + throw new Error(`Error fetching ${url}: ${fallbackResponse.status} ${fallbackResponse.statusText}`); + } catch (fallbackError) { + console.error(`Fallback fetching without User-Agent failed:`, fallbackError); + return { + response: undefined, + error: `Error fetching ${url}: ${fallbackError}` + }; + } + } } /**