fixing btc

This commit is contained in:
martind2000 2017-06-12 13:37:38 +01:00
parent 3d444486f1
commit bcc7a3d87e

View File

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