import { ExchangeRate } from '../types.js';
const API_BASE = 'https://api.exchangerate-api.com/v4/latest';
interface ExchangeRateApiResponse {
base: string;
date: string;
rates: Record<string, number>;
}
export async function getRate(from: string, to: string): Promise<ExchangeRate> {
const fromUpper = from.toUpperCase();
const toUpper = to.toUpperCase();
const response = await fetch(`${API_BASE}/${fromUpper}`);
if (!response.ok) {
throw new Error(`Failed to fetch exchange rates: ${response.statusText}`);
}
const data: ExchangeRateApiResponse = await response.json();
if (!data.rates[toUpper]) {
throw new Error(`Currency ${toUpper} not found`);
}
return {
base: fromUpper,
target: toUpper,
rate: data.rates[toUpper],
timestamp: data.date
};
}
export async function convert(
amount: number,
from: string,
to: string
): Promise<{
original: { amount: number; currency: string };
converted: { amount: number; currency: string };
rate: number;
}> {
const exchangeRate = await getRate(from, to);
const convertedAmount = amount * exchangeRate.rate;
return {
original: { amount, currency: exchangeRate.base },
converted: { amount: Math.round(convertedAmount * 100) / 100, currency: exchangeRate.target },
rate: exchangeRate.rate
};
}
export async function getMultipleRates(
base: string,
targets: string[]
): Promise<{
base: string;
rates: Array<{ currency: string; rate: number; conversion: string }>;
timestamp: string;
}> {
const baseUpper = base.toUpperCase();
const response = await fetch(`${API_BASE}/${baseUpper}`);
if (!response.ok) {
throw new Error(`Failed to fetch exchange rates: ${response.statusText}`);
}
const data: ExchangeRateApiResponse = await response.json();
const rates = targets.map(target => {
const targetUpper = target.toUpperCase();
const rate = data.rates[targetUpper];
if (!rate) {
throw new Error(`Currency ${targetUpper} not found`);
}
return {
currency: targetUpper,
rate,
conversion: `1 ${baseUpper} = ${rate} ${targetUpper}`
};
});
return {
base: baseUpper,
rates,
timestamp: data.date
};
}