npm install --save request
node bitcoin-price.js
Last active
November 25, 2018 14:14
-
-
Save emersonbroga/181464881868f2aa164d57df59e1fc59 to your computer and use it in GitHub Desktop.
Bitcoin value with Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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