In this example, the CurrencyExchangeAPI class has two methods: getExchangeRate and convertCurrency.
The getExchangeRate method makes a GET request to the Exchange Rates API to get the latest exchange rates for a given base currency. It then extracts the exchange rate for the target currency from the response and returns it. If the exchange rate for the target currency is not available, an error is thrown.
The convertCurrency method uses the getExchangeRate method to get the exchange rate for the base and target currencies, and then multiplies the amount to be converted by the exchange rate to get the converted amount.
To use this API client, you would create an instance of the CurrencyExchangeAPI class, passing your API key as a parameter. You can then call the convertCurrency method with the base currency, target currency, and amount to be converted.
The result is returned as a Promise, which you can handle with then and catch methods.
Here's a full implementation of the CurrencyExchangeAPI class:
In this implementation, the CurrencyExchangeAPI class is defined with a constructor that takes an apiKey parameter and sets the baseURL property to the URL of the exchange rate API. The class also defines two async methods: getExchangeRate and convertCurrency.
The getExchangeRate method takes a baseCurrency and targetCurrency parameter, and makes an HTTP request to the exchange rate API using the fetch function. The response is then parsed as JSON, and the exchange rate is extracted from the response using the rates property. If the exchange rate exists, it is returned, otherwise an error is thrown.
The convertCurrency method takes a baseCurrency, targetCurrency, and amount parameter, and uses the getExchangeRate method to retrieve the exchange rate between the two currencies. The method then returns the converted amount by multiplying the exchange rate with the original amount.
Finally, an example usage of the CurrencyExchangeAPI class is provided, where an instance of the class is created with an API key, and the convertCurrency method is called to convert 100 USD to EUR. The result is then logged to the console, or an error is caught and logged if one occurs.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (