silvrgit/lib/fx.js
2018-01-14 11:17:07 +00: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 = 5529600; // 32 days divided by 500
let fxCache = {};
const history = new LimitedArray(48); // one days worth in 5 minute chunks
function getFx() {
logger.info('FX request');
function fxQuery(callback) {
const 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;
fxCache.rates = { 'USD': fxCache.rates.USD, 'GBP': fxCache.rates.GBP, 'SEK': fxCache.rates.SEK };
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();
// 1517443200000
// 1505696400000
if (now.getTime() > 1517443200000)
getFx();
const mod = delay - (now.getTime() % delay);
const 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));
};