Created
February 9, 2024 10:55
-
-
Save sorich87/5026b03ad4482b985b6047040088c6e4 to your computer and use it in GitHub Desktop.
Currency conversion with Currency API
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 COUNTRY_CURRENCY: { [key: string]: string } = { | |
BJ: "XOF", | |
BF: "XOF", | |
CD: "CDF", | |
CI: "XOF", | |
CG: "XAF", | |
CM: "XAF", | |
GA: "XAF", | |
GH: "GHS", | |
GN: "GNF", | |
KE: "KES", | |
LR: "LRD", | |
MG: "MGA", | |
ML: "XOF", | |
MW: "MWK", | |
NE: "XOF", | |
RW: "RWF", | |
SN: "XOF", | |
TG: "XOF", | |
TZ: "TZS", | |
UG: "UGX", | |
ZM: "ZMW", | |
}; | |
export function countryCurrency(country: string) { | |
return COUNTRY_CURRENCY[country]; | |
} | |
export async function amountInCurrency(amount: number, country: string) { | |
const currency = countryCurrency(country); | |
if (["XAF", "XOF"].includes(currency)) return amount; | |
const lowercaseCurrency = currency.toLowerCase(); | |
const response = await fetch( | |
`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/xof/${lowercaseCurrency}.json`, | |
{ | |
method: "GET", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}, | |
); | |
const data = await response.text(); | |
const json = JSON.parse(data); | |
const exchangeRate = json[lowercaseCurrency]; | |
return Math.ceil(amount * exchangeRate * 1.02); | |
} | |
export function currencyFormatter(currency: string) { | |
return new Intl.NumberFormat("fr-FR", { | |
style: "currency", | |
currency, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment