npm install --save request
node index.js
Created
June 5, 2019 13:28
-
-
Save emersonbrogadev/a397739c7f541eb7ed5f493902fd5b51 to your computer and use it in GitHub Desktop.
This file contains 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 = (data) => { | |
try { | |
return JSON.parse(data); | |
} catch (error) { | |
return null; | |
} | |
}; | |
const formatValue = (value, currencySymbol) => { | |
const parsedValue = (isNaN(value)) ? 0 : parseFloat(value, 10); | |
return `${currencySymbol} ${parsedValue.toFixed(2)}`; | |
}; | |
const doRequest = (url, dataResolver) => { | |
const promiseCallback = (resolve, reject) => { | |
const callback = (error, httpResponse, body) => { | |
if (error) return reject(error); | |
const response = parseJSON(body); | |
const price = (response) ? dataResolver(response) : null; | |
resolve(price); | |
}; | |
request(url, callback); | |
} | |
return new Promise(promiseCallback); | |
}; | |
const getPriceCoinbase = () => { | |
const url = 'https://api.coinbase.com/v2/prices/spot?currency=USD'; | |
const dataResolver = (response) => formatValue(response.data.amount, 'U$'); | |
return doRequest(url, dataResolver); | |
}; | |
const getPriceBitcoinTrade = () => { | |
const url = 'https://api.bitcointrade.com.br/v2/public/BRLBTC/ticker'; | |
const dataResolver = (response) => formatValue(response.data.last, 'R$'); | |
return doRequest(url, dataResolver); | |
}; | |
(async () => { | |
const [priceBitcoinTrade, priceCoinbase] = await Promise.all([ | |
getPriceBitcoinTrade(), | |
getPriceCoinbase(), | |
]); | |
const text = `${priceBitcoinTrade} | ${priceCoinbase}`; | |
console.log(text); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment