From a26a7938ad1edf7903e03aca6c109674dc29bfb5 Mon Sep 17 00:00:00 2001 From: Nathan Woodburn Date: Mon, 30 Dec 2024 19:38:31 +1100 Subject: [PATCH] feat: Add backup api for cross site blocks --- templates/index.html | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/templates/index.html b/templates/index.html index 7b8754f..fecdf02 100644 --- a/templates/index.html +++ b/templates/index.html @@ -42,14 +42,41 @@ }; async function fetchJoke() { - const response = await fetch('https://icanhazdadjoke.com', { - headers: { - 'Accept': 'application/json' + try { + let response; + + // Attempt to fetch the external API first + try { + response = await fetch('https://icanhazdadjoke.com/', { + headers: { + 'Accept': 'application/json' + } + }); + + // If the external API response is not ok, fallback to local API + if (!response.ok) { + throw new Error('External API failed'); + } + } catch (error) { + console.warn('External API failed:', error); + // Fall back to local API after external API failure + response = await fetch('/api/joke'); + + // If local API also fails, throw an error + if (!response.ok) { + throw new Error('Both external and local APIs failed'); + } } - }); - const data = await response.json(); - document.getElementById('joke').innerText = data.joke; + + // Parse and display the joke + const data = await response.json(); + document.getElementById('joke').innerText = data.joke; + } catch (error) { + console.error('Failed to fetch joke:', error); + document.getElementById('joke').innerText = "Oops! Couldn't fetch a joke right now."; + } } +