silvrgit/lib/fx.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-03-22 17:01:58 +00:00
const http = require('http');
2017-08-18 14:08:28 +00:00
const LimitedArray = require('limitedarray');
const trend = require('trend');
const logger = require('log4js').getLogger('fx');
2017-08-20 22:20:43 +00:00
const delay = (60000 * 30);
2017-03-22 17:01:58 +00:00
let fxCache = {};
2017-08-20 22:20:43 +00:00
let history = new LimitedArray(48); // one days worth in 5 minute chunks
2017-08-18 14:08:28 +00:00
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;
history.push(a.rates.GBP);
fxCache.history = history.get();
2017-08-20 22:20:43 +00:00
fxCache.trend = trend(fxCache.history, {avgPoints: 12});
2017-08-18 14:08:28 +00:00
});
}
function updateFX() {
logger.warn('updateBitcoin');
getFx();
const now = new Date();
2017-08-20 22:20:43 +00:00
const mod = delay - (now.getTime() % delay);
2017-08-18 14:08:28 +00:00
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));
2016-03-08 21:52:21 +00:00
};