52 lines
1.4 KiB
JavaScript
52 lines
1.4 KiB
JavaScript
const express = require('express'), http = require('http');
|
|
const router = express.Router();
|
|
let btcCache = {};
|
|
|
|
/* GET users listing. */
|
|
router.get('/', function(req, res, next) {
|
|
console.log('Bitcoin request');
|
|
function btcQuery(callback, r) {
|
|
const req = r;
|
|
const 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) {
|
|
let data = '';
|
|
response.on('data', function (chunk) {
|
|
data += chunk;
|
|
});
|
|
response.on('end', function () {
|
|
callback(JSON.parse(data), r);
|
|
});
|
|
}).end();
|
|
}
|
|
|
|
const now = new Date();
|
|
if (now - GLOBAL.lastcheck.btc > (59000 ))
|
|
btcQuery(function (a, b) {
|
|
console.log(a);
|
|
btcCache = a;
|
|
GLOBAL.lastcheck.btc = now;
|
|
res.writeHead(200, { 'ContentType': 'application/json' });
|
|
// res.setHeader('Content-Type', 'application/json');
|
|
res.end(JSON.stringify(btcCache));
|
|
}, res);
|
|
|
|
else {
|
|
console.log('Using cache');
|
|
// res.setHeader('Content-Type', 'application/json');
|
|
res.writeHead(200, { 'ContentType': 'application/json' });
|
|
res.end(JSON.stringify(btcCache));
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|