We can use the Open Exchange Rates API to get the current exchange rate between currencies.
We need the request package in order to perform remote requests:
npm install request --save
Then we can create the following class:
'use strict';
const request = require('request');
const appID = 'app ID';
class Currency {
constructor(from = 'USD', to = 'EUR') {
this.from = from;
this.to = to;
this.url = 'https://openexchangerates.org/api/latest.json';
}
getRate() {
let self = this;
let query = {
app_id: appID,
base: self.from
};
let options = {
url: self.url,
qs: query,
timeout: 5000
};
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (!error) {
let data = JSON.parse(body);
resolve(data);
} else {
reject({
error: error
});
}
});
});
}
}
module.exports = Currency;
For direct conversions you can also use the /convert API endpoint.