Exchange Class
The Exchange class handles currency conversion with live exchange rates.
Constructor
new Exchange(source?: CurrencyCode, target?: CurrencyCode, amount?: number)Create a new Exchange instance.
Parameters:
source- Source currency code (optional)target- Target currency code (optional)amount- Amount to convert (optional, default: 1)
Example:
const exchange = new Exchange('USD', 'EUR', 100);Static Methods
setApiKey()
Exchange.setApiKey(key: string): voidSet the API key for exchange rate requests.
Example:
Exchange.setApiKey('your-api-key-here');Getting an API Key:
- Sign up at exchangerate-api.com
- Get your free API key
- Set it using
Exchange.setApiKey()or viaEXCHANGERATE_API_KEYenvironment variable
from()
Exchange.from(currency: CurrencyCode): ExchangeCreate an Exchange instance with source currency (static method).
Example:
const exchange = Exchange.from('USD');to()
Exchange.to(currency: CurrencyCode): ExchangeCreate an Exchange instance with target currency (static method).
Example:
const exchange = Exchange.to('EUR');format()
Exchange.format(amount: number, from: CurrencyCode, to: CurrencyCode): Promise<string>Convert and format amount in one call (static method).
Example:
const formatted = await Exchange.format(100, 'USD', 'EUR');
// e.g., "€92.50"Instance Methods
from()
from(currency: CurrencyCode): thisSet the source currency.
Example:
exchange.from('USD');to()
to(currency: CurrencyCode): thisSet the target currency.
Example:
exchange.to('EUR');convert()
convert(amount: number, source?: CurrencyCode, target?: CurrencyCode): thisSet conversion parameters. Returns this for chaining.
Example:
const result = await exchange.convert(100);
// or with optional parameters
const result = await exchange.convert(100, 'USD', 'EUR');rate()
rate(source?: CurrencyCode, target?: CurrencyCode): thisGet exchange rate. Returns this for chaining.
Example:
const rate = await exchange.rate('USD', 'EUR');
// or chained
const rate = await exchange.from('USD').to('EUR').rate();format()
format(): Promise<string>Format the converted amount with currency symbol.
Example:
const formatted = await exchange.from('USD').to('EUR').convert(100).format();
// e.g., "€92.50"Thenable Interface
The Exchange class implements a "thenable" interface for seamless async/await integration.
then()
then<T>(
onFulfilled?: (value: number) => T | PromiseLike<T>,
onRejected?: (reason: any) => T | PromiseLike<T>
): Promise<T>Execute the conversion chain.
Example:
exchange
.from('USD')
.to('EUR')
.convert(100)
.then((result) => console.log(result));catch()
catch<T>(onRejected?: (reason: any) => T | PromiseLike<T>): Promise<T>Catch errors in the conversion chain.
Example:
exchange
.from('USD')
.to('EUR')
.convert(100)
.catch((error) => console.error(error));finally()
finally(onFinally?: (() => void) | null): Promise<number>Execute cleanup after conversion.
Example:
exchange
.from('USD')
.to('EUR')
.convert(100)
.finally(() => console.log('Done'));How Thenable Works
The thenable pattern allows methods to return this synchronously for chaining, while async execution only happens when awaited or .then() is called:
// Build chain (synchronous)
const chain = exchange.from('USD').to('EUR').convert(100);
// Execute (asynchronous)
const result = await chain;
// Or with callbacks
chain
.then((result) => console.log(result))
.catch((error) => console.error(error))
.finally(() => console.log('Complete'));Error Handling
try {
const result = await Exchange.from('USD').to('EUR').convert(100);
} catch (error) {
if (error.type === 'missing-key') {
console.error('Please set your API key');
} else {
console.error('Conversion error:', error.message);
}
}Environment Variables
The library automatically loads the .env file if it exists. You can set:
# .env file
EXCHANGERATE_API_KEY=your-api-key-hereNo need to call Exchange.setApiKey() if the environment variable is set.
