The source currency code (e.g., 'USD', 'EUR')
The target currency code
The exchange rate as a number
Error if the API request fails or rate cannot be fetched
// Get EUR to USD rate
const rate = await getCurrencyRate('EUR', 'USD')
// Returns something like 1.18 (meaning 1 EUR = 1.18 USD)
// Convert amount using rate
const amount = 100;
const converted = amount * rate; // 118 USD
// Rates are cached for subsequent calls
await getCurrencyRate('EUR', 'USD') // Uses cached value
export async function getCurrencyRate(from: CurrencyCode, to: CurrencyCode): Promise<number> {
try {
return await lruCurrencyRate.fetch(`${from}:${to}`);
} catch (error) {
throw new Error(
`Failed to get currency rate for ${from} to ${to} - ${error instanceof Error ? error.message : String(error)}`,
);
}
}
Fetches the current exchange rate between two currencies. Uses the Hexarate API to get real-time exchange rates. Implements caching using LRU cache to minimize API calls.