From fa55777d506d20c13b484022c4a3e0243ed326db Mon Sep 17 00:00:00 2001 From: printfn Date: Thu, 7 Mar 2024 09:16:17 +0000 Subject: [PATCH] Use cloudflare worker as a CORS proxy --- web/cf-worker.js | 30 ++++++++++++++++++++++++++++++ web/widget.js | 21 +++++++++++++-------- 2 files changed, 43 insertions(+), 8 deletions(-) create mode 100644 web/cf-worker.js diff --git a/web/cf-worker.js b/web/cf-worker.js new file mode 100644 index 00000000..cb312d56 --- /dev/null +++ b/web/cf-worker.js @@ -0,0 +1,30 @@ +// This needs to be manually deployed to Cloudflare + +export default { + async fetch(request, env, ctx) { + if ( + request.url === 'https://fend.pr.workers.dev/exchange-rates' && + request.method === 'GET' + ) { + const fetchResult = await fetch( + 'https://treasury.un.org/operationalrates/xsql2XML.php', + { + headers: { + 'X-Source': 'Cloudflare-Workers', + }, + }, + ); + const data = await fetchResult.text(); + return new Response(data, { + headers: { + 'Access-Control-Allow-Origin': 'https://printfn.github.io', + 'Cache-Control': 'max-age=172800', + }, + }); + } else { + return new Response(null, { + status: 404, + }); + } + }, +}; diff --git a/web/widget.js b/web/widget.js index f504b708..7a5b0ea9 100644 --- a/web/widget.js +++ b/web/widget.js @@ -178,11 +178,7 @@ async function getExchangeRates() { const map = new Map(); try { - const res = await fetch( - `https://corsproxy.io/?${encodeURIComponent( - 'https://treasury.un.org/operationalrates/xsql2XML.php', - )}`, - ); + const res = await fetch('https://fend.pr.workers.dev/exchange-rates'); const xml = await res.text(); const dom = new DOMParser().parseFromString(xml, 'text/xml'); @@ -200,10 +196,19 @@ async function getExchangeRates() { } async function load() { - await wasm_bindgen('./pkg/fend_wasm_bg.wasm'); - initialiseWithHandlers(await getExchangeRates()); + try { + await wasm_bindgen('./pkg/fend_wasm_bg.wasm'); + initialiseWithHandlers(await getExchangeRates()); - evaluateFendWithTimeout('1 + 2', 500); + const result = evaluateFendWithTimeout('1 + 2', 500); + if (result !== '3') { + alert('Failed to initialise WebAssembly'); + return; + } + } catch (e) { + alert('Failed to initialise WebAssembly'); + return; + } wasmInitialised = true; inputText.addEventListener('input', update);