silvrgit/lib/btc.js

52 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-04-05 13:22:31 +00:00
let http = require('http');
let btcCache = {};
exports.doBTC = function(req, res) {
console.log('Bitcoin request');
function btcQuery(callback, r) {
var req = r;
var options = {
host: 'api.coindesk.com',
2016-03-08 21:52:21 +00:00
// port: 80,
2017-04-05 13:22:31 +00:00
path: '/v1/bpi/currentprice.json',
2016-03-08 21:52:21 +00:00
// method: 'GET',
2017-04-05 13:22:31 +00:00
headers: {
2016-03-08 21:52:21 +00:00
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
}
};
2017-04-05 13:22:31 +00:00
try {
http.request(options).on('response', function(response) {
var data = '';
response.on('data', function(chunk) {
data += chunk;
2016-03-08 21:52:21 +00:00
});
2017-04-05 13:22:31 +00:00
response.on('end', function() {
callback(JSON.parse(data), r);
2016-03-08 21:52:21 +00:00
});
2016-03-23 16:04:45 +00:00
response.on('error', function(e) {
2017-04-05 13:22:31 +00:00
console.error(e);
});
2016-03-08 21:52:21 +00:00
}).end();
2016-03-23 16:04:45 +00:00
} catch (e) {
2017-04-05 13:22:31 +00:00
console.error(e);
}
2016-03-08 21:52:21 +00:00
}
2017-04-05 13:22:31 +00:00
let now = new Date();
if (now - GLOBAL.lastcheck > (59000 )) {
btcQuery(function(a) {
2016-03-08 21:52:21 +00:00
// console.log(a);
2017-04-05 13:22:31 +00:00
console.log('Got btc data.');
btcCache = a;
GLOBAL.lastcheck = now;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(btcCache));
}, res);
} else {
console.log('Using cache');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(btcCache));
2016-03-08 21:52:21 +00:00
}
2017-04-05 13:22:31 +00:00
};