silvrgit/lib/fx.js
2017-09-05 12:12:42 +01:00

72 lines
1.7 KiB
JavaScript

const http = require('http');
const LimitedArray = require('limitedarray');
const trend = require('trend');
const logger = require('log4js').getLogger('fx');
const delay = 2764800; // 32 days divided by 1000
let fxCache = {};
let history = new LimitedArray(48); // one days worth in 5 minute chunks
function getFx() {
logger.info('FX request');
function fxQuery(callback) {
let options = {
host: 'openexchangerates.org',
// port: 80,
path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
// method: 'GET',
headers: { }
};
http.request(options).on('response', response => {
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
logger.info('Data done...');
callback(JSON.parse(data));
});
response.on('error', e => {
logger.error(e);
});
}).end();
}
fxQuery(a => {
logger.info('Got FX data. Storing it');
fxCache = a;
let minRates = {USD:fxCache.rates.USD, GBP:fxCache.rates.GBP, SEK:fxCache.rates.SEK};
fxCache.rates = minRates;
history.push(a.rates.GBP);
fxCache.history = history.get();
fxCache.trend = trend(fxCache.history, {avgPoints: 12});
});
}
function updateFX() {
logger.warn('updateBitcoin');
const now = new Date();
if (now.getTime() > 1505696400000)
getFx();
const mod = delay - (now.getTime() % delay);
let fxUpdateFn = () => {
updateFX();
};
setTimeout(fxUpdateFn.bind(this), mod + 10);
}
updateFX();
exports.doFx = (req, res) => {
logger.info('FX request');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(fxCache));
};