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}` + }; + } + } } /**