Skip to content

Commit

Permalink
Use cloudflare worker as a CORS proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
printfn committed Mar 7, 2024
1 parent 211c066 commit fa55777
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
30 changes: 30 additions & 0 deletions web/cf-worker.js
Original file line number Diff line number Diff line change
@@ -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,
});
}
},
};
21 changes: 13 additions & 8 deletions web/widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand All @@ -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);
Expand Down

0 comments on commit fa55777

Please sign in to comment.