silvrgit/lib/fx.js

53 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-03-22 17:01:58 +00:00
const http = require('http');
let fxCache = {};
2016-03-08 21:52:21 +00:00
exports.doFx = function (req,res) {
console.log('FX request');
function fxQuery(callback, r) {
2017-04-02 22:42:24 +00:00
let req = r;
let options = {
2016-03-08 21:52:21 +00:00
host: 'openexchangerates.org',
// port: 80,
path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
// method: 'GET',
headers: {
/* 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)*/
}
};
http.request(options).on('response', function (response) {
2017-04-02 22:42:24 +00:00
let data = '';
2016-03-08 21:52:21 +00:00
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
2017-03-22 17:01:58 +00:00
console.log('Data done...');
2016-03-08 21:52:21 +00:00
callback(JSON.parse(data), r);
});
2016-03-23 16:04:45 +00:00
response.on('error', function(e) {
console.error(e);
});
2016-03-08 21:52:21 +00:00
}).end();
}
2017-04-02 22:42:24 +00:00
let now = new Date();
if (now - GLOBAL.fxLastCheck > (60000 * 14)) {
2016-03-08 21:52:21 +00:00
fxQuery(function (a, b) {
console.log(a);
fxCache = a;
2017-04-02 22:42:24 +00:00
GLOBAL.fxLastCheck = now;
2016-03-08 21:52:21 +00:00
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(fxCache));
}, res);
}
else {
console.log("Using cache");
res.setHeader('Content-Type', 'application/json');
2017-03-22 17:01:58 +00:00
console.log('Cache length:', JSON.stringify(fxCache).length);
console.log(JSON.stringify(fxCache).substring(0,50));
2016-03-08 21:52:21 +00:00
res.end(JSON.stringify(fxCache));
}
};