Skip to content

Instantly share code, notes, and snippets.

@tuhuynh27
Created May 19, 2023 09:21
Show Gist options
  • Save tuhuynh27/a67edeec13c9632d7c79c3652fb211de to your computer and use it in GitHub Desktop.
Save tuhuynh27/a67edeec13c9632d7c79c3652fb211de to your computer and use it in GitHub Desktop.
Wise money rate crawler
const fromCurrency = searchParams.get('from') || 'SGD';
const toCurrency = searchParams.get('to') || 'VND';
let response;
async function getRate(fromCurrency, toCurrency) {
// Fetch the exchange rate from Wise
response = await fetch(`https://wise.com/gb/currency-converter/${fromCurrency.toLowerCase()}-to-${toCurrency.toLowerCase()}-rate?amount=1`);
// Extract the exchange rate from the response
const html = await response.text();
function findString(target, str) {
const index = str.indexOf(target);
if (index === -1) {
return -1;
} else {
return str.substring(index + target.length, index + target.length + 30);
}
}
function extractNumber(str) {
const numberRegex = /-?\d+(\.\d+)?/;
const match = str.match(numberRegex);
if (match) {
return Number(match[0]);
} else {
return null;
}
}
const est = findString(`text-success`, html);
if (est === -1) {
return null;
}
return extractNumber(est);
}
const r = await getRate(fromCurrency, toCurrency);
if (!r) {
return new Response(JSON.stringify({ error: true, code: response.status, statusText: response.statusText }), {
code: response.status,
statusText: response.statusText,
headers: {'Content-Type': 'application/json'},
})
}
return new Response(JSON.stringify({
data: r
}), {
headers: {
...corsHeaders,
'Content-Type': 'application/json',
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment