Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bitcoin value with Javascript
const request = require('request');
const parseJson = (string) => {
try{
return JSON.parse(string);
}catch(e) {
return null;
}
}
const formatWithCurrency = (value, currencySymbol) => {
const parsed = parseFloat(value, 10);
if (isNaN(value) || isNaN(parsed)) { return 0 }
return currencySymbol + ' ' + parsed.toFixed(2).toString();
}
const doRequest = (url, dataResolver) =>{
const req = (resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
const data = parseJson(body);
resolve(dataResolver(data));
});
};
return new Promise(req);
}
const getPriceCoinbase = () => {
const dataResolver = (data) => {
return (data) ? formatWithCurrency(data.data.amount, 'U$') : null;
};
return doRequest('https://api.coinbase.com/v2/prices/spot?currency=USD', dataResolver);
}
const getPriceBitcoinTrade = () => {
const dataResolver = (data) => {
return (data) ? formatWithCurrency(data.data.last, 'R$') : null;
};
return doRequest('https://api.bitcointrade.com.br/v1/public/BTC/ticker/', dataResolver);
}
(async () => {
const [bitcointrade, coinbase] = await Promise.all([getPriceBitcoinTrade(), getPriceCoinbase()]);
const text = `${bitcointrade} | ${coinbase}`;
console.log(text);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment