← back to Watches

services/exchange-rates.js

39 lines

/**
 * Exchange Rate Service
 * Fetches live rates from free API with caching
 */

const API_URL = 'https://api.exchangerate-api.com/v4/latest/USD';
let cachedRates = null;
let cacheTime = 0;
const CACHE_TTL = 60 * 60 * 1000; // 1 hour

export async function getExchangeRates() {
  if (cachedRates && Date.now() - cacheTime < CACHE_TTL) return cachedRates;

  try {
    const response = await fetch(API_URL);
    const data = await response.json();
    cachedRates = data.rates;
    cacheTime = Date.now();
    return cachedRates;
  } catch (error) {
    console.error('Exchange rate fetch failed:', error);
    return cachedRates || { USD: 1, EUR: 0.92, GBP: 0.79, JPY: 150, CHF: 0.88, AUD: 1.53, CAD: 1.36 };
  }
}

export async function convertCurrency(amount, from, to) {
  const rates = await getExchangeRates();
  if (from === 'USD') return amount * rates[to];
  if (to === 'USD') return amount / rates[from];
  return (amount / rates[from]) * rates[to];
}

export async function getRate(currency) {
  const rates = await getExchangeRates();
  return rates[currency] || 1;
}

export default { getExchangeRates, convertCurrency, getRate };