silvrgit/lib/fx.js
2017-04-02 23:42:24 +01:00

53 lines
1.8 KiB
JavaScript

const http = require('http');
let fxCache = {};
exports.doFx = function (req,res) {
console.log('FX request');
function fxQuery(callback, r) {
let req = r;
let options = {
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) {
let data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log('Data done...');
callback(JSON.parse(data), r);
});
response.on('error', function(e) {
console.error(e);
});
}).end();
}
let now = new Date();
if (now - GLOBAL.fxLastCheck > (60000 * 14)) {
fxQuery(function (a, b) {
console.log(a);
fxCache = a;
GLOBAL.fxLastCheck = now;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(fxCache));
}, res);
}
else {
console.log("Using cache");
res.setHeader('Content-Type', 'application/json');
console.log('Cache length:', JSON.stringify(fxCache).length);
console.log(JSON.stringify(fxCache).substring(0,50));
res.end(JSON.stringify(fxCache));
}
};