old-silvrgit/lib/btc.js
2016-02-18 11:10:44 +00:00

47 lines
1.5 KiB
JavaScript

var http = require('http');
var btcCache = {};
exports.doBTC = function (req,res) {
console.log('Bitcoin request');
function btcQuery(callback, r) {
var req = r;
var options = {
host: 'api.coindesk.com',
// port: 80,
path: '/v1/bpi/currentprice.json',
// method: 'GET',
headers: {
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
}
};
http.request(options).on('response', function (response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
callback(JSON.parse(data), r);
});
}).end();
}
var now = new Date();
if (now - GLOBAL.lastcheck > (59000 )) {
btcQuery(function (a, b) {
// console.log(a);
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));
}
};