Exchange Rate Tracker via API JavaScript, API
👤 Sharing: AI
```javascript
/**
* Exchange Rate Tracker via API
*
* This script fetches exchange rates from a public API (e.g., ExchangeRate-API)
* and provides functions to get the latest exchange rate for a given currency pair.
*
* **Important:** Replace `YOUR_API_KEY` with a valid API key from the
* ExchangeRate-API service (or a similar service). Without a valid key,
* the code will not function.
*/
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const apiBaseUrl = 'https://v6.exchangerate-api.com/v6/'; //ExchangeRate-API endpoint. Update for other APIs
const defaultBaseCurrency = 'USD'; // Set the default base currency
/**
* Fetches exchange rates from the API.
*
* @param {string} baseCurrency - The base currency for the exchange rates.
* @returns {Promise<object>} - A promise that resolves to the exchange rates data as a JSON object.
* Rejects if there is an error fetching the data.
*/
async function fetchExchangeRates(baseCurrency = defaultBaseCurrency) {
try {
const url = `${apiBaseUrl}${apiKey}/latest/${baseCurrency}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if (data.result !== 'success') {
throw new Error(`API error: ${data['error-type']}`); //Adjust error handling based on API
}
return data;
} catch (error) {
console.error('Error fetching exchange rates:', error);
throw error; // Re-throw the error to be handled by the caller
}
}
/**
* Gets the exchange rate for a given currency pair.
*
* @param {string} baseCurrency - The base currency.
* @param {string} targetCurrency - The target currency.
* @returns {Promise<number>} - A promise that resolves to the exchange rate.
* Rejects if the exchange rate cannot be found or if there is an API error.
*/
async function getExchangeRate(baseCurrency, targetCurrency) {
try {
const data = await fetchExchangeRates(baseCurrency);
if (!data.conversion_rates || !data.conversion_rates[targetCurrency]) {
throw new Error(`Exchange rate not found for ${baseCurrency} to ${targetCurrency}`);
}
return data.conversion_rates[targetCurrency];
} catch (error) {
console.error(`Error getting exchange rate for ${baseCurrency} to ${targetCurrency}:`, error);
throw error; // Re-throw the error
}
}
/**
* Example usage of the functions.
*/
async function main() {
try {
const usdToEurRate = await getExchangeRate('USD', 'EUR');
console.log(`1 USD = ${usdToEurRate} EUR`);
const gbpToJpyRate = await getExchangeRate('GBP', 'JPY');
console.log(`1 GBP = ${gbpToJpyRate} JPY`);
const cadToUsdRate = await getExchangeRate('CAD', 'USD');
console.log(`1 CAD = ${cadToUsdRate} USD`);
} catch (error) {
console.error('An error occurred:', error);
}
}
// Execute the main function
main();
// --- Additional features and considerations (not implemented in the base code): ---
// 1. Currency Symbol Display: The API response typically *does not* include currency symbols. You would need to use a separate library or data source to map currency codes (e.g., 'USD', 'EUR') to their corresponding symbols ('$', '?').
// 2. Local Storage Caching: To avoid making excessive API calls, you can cache the exchange rate data in local storage (or cookies) for a short period (e.g., 15 minutes to an hour). Check the cache before making an API call. Remember that exchange rates change frequently.
// 3. Error Handling Enhancement: Implement more robust error handling, including retries (with exponential backoff) for transient network errors.
// 4. User Interface: If you want a user interface (e.g., a web page), you'll need to use HTML, CSS, and JavaScript to create input fields for the base and target currencies and a display area for the exchange rate. Consider using a framework like React, Vue, or Angular for more complex UIs.
// 5. Currency Validation: Validate that the user-provided currency codes are valid ISO 4217 currency codes before making API requests.
// 6. Loading Indicators: Show a loading indicator while fetching data from the API to provide visual feedback to the user.
// 7. Rate Limiting: Be mindful of the API's rate limits. Implement strategies to avoid exceeding the limits (e.g., caching, queuing requests, displaying a message to the user if the rate limit is reached).
// 8. Data Persistence: Consider persisting the exchange rate data in a database if you need to track historical rates or analyze trends.
```
👁️ Viewed: 104
Comments