-
Notifications
You must be signed in to change notification settings - Fork 3
/
helpers.js
60 lines (53 loc) · 2.2 KB
/
helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const axios = require('axios')
const { symbol, pair, url } = require('./constants')
const formatResponse = (value, currency) => `1 btc is equal to ${symbol[currency]} ${parseFloat(value).toFixed(2)}`
const rawRequest = (exchange, currency) => {
switch(exchange) {
case 'kraken':
return new Promise((resolve, reject) => {
axios.post(
url[exchange],
{
pair: pair[currency],
headers: { 'Api-Key': config.apiKey, 'Api-Sign': config.apiSecret }
}
)
.then(({ data }) => resolve(data.result ? formatResponse(data.result[pair[currency]].c[0], currency) : 'An error occured, retry'))
.catch(error => {
console.log(error)
reject('Timeout error, please retry')
})
})
case 'coinbase':
return new Promise((resolve, reject) => {
axios.get(`${url[exchange]}BTC-${currency.toUpperCase()}/spot`, { headers: { 'CB-VERSION': '2015-04-08' } })
.then(({ data }) => resolve(data && data.data && data.data.amount ? formatResponse(data.data.amount, currency) : 'An error occured, retry'))
.catch(error => {
console.log(error)
reject('Timeout error, please retry')
})
})
case 'bitcoinaverage':
return new Promise((resolve, reject) => {
axios.get(`${url[exchange]}BTC${currency.toUpperCase()}`)
.then(({ data }) => resolve(data.last ? formatResponse(data.last, currency) : 'An error occured, retry'))
.catch(error => {
console.log(error)
reject('Timeout error, please retry')
})
})
default:
return new Promise((resolve, reject) => {
axios.get(`${url[exchange]}?convert=${currency.toUpperCase()}`)
.then(({ data }) => {
const rawResponse = data.find(elem => elem.symbol.toLowerCase() === 'btc')
resolve(rawResponse && rawResponse[`price_${currency}`] ? formatResponse(rawResponse[`price_${currency}`], currency) : 'An error occured, retry')
})
.catch(error => {
console.log(error)
reject('Timeout error, please retry')
})
})
}
}
module.exports = rawRequest