Created
May 19, 2023 09:21
-
-
Save tuhuynh27/a67edeec13c9632d7c79c3652fb211de to your computer and use it in GitHub Desktop.
Wise money rate crawler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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