Skip to content

Instantly share code, notes, and snippets.

@sorich87
Created February 9, 2024 10:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorich87/5026b03ad4482b985b6047040088c6e4 to your computer and use it in GitHub Desktop.
Save sorich87/5026b03ad4482b985b6047040088c6e4 to your computer and use it in GitHub Desktop.
Currency conversion with Currency API
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