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-09-05 10:36:24 +00:00
|
|
|
const delay = 2764800; // 32 days divided by 1000
|
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;
|
|
|
|
|
2017-09-05 10:36:24 +00:00
|
|
|
let minRates = {USD:fxCache.rates.USD, GBP:fxCache.rates.GBP, SEK:fxCache.rates.SEK};
|
|
|
|
fxCache.rates = minRates;
|
2017-08-18 14:08:28 +00:00
|
|
|
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
|
|
|
|
|
|
|
};
|