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-09-06 07:42:13 +00:00
|
|
|
const 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) {
|
2017-09-06 07:42:13 +00:00
|
|
|
const options = {
|
|
|
|
'host': 'openexchangerates.org',
|
|
|
|
// port: 80,
|
|
|
|
'path': '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
|
2017-08-18 14:08:28 +00:00
|
|
|
// method: 'GET',
|
2017-09-06 07:42:13 +00:00
|
|
|
'headers': { }
|
2017-08-18 14:08:28 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
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-06 07:42:13 +00:00
|
|
|
fxCache.rates = { 'USD': fxCache.rates.USD, 'GBP': fxCache.rates.GBP, 'SEK': fxCache.rates.SEK };
|
2017-08-18 14:08:28 +00:00
|
|
|
history.push(a.rates.GBP);
|
|
|
|
fxCache.history = history.get();
|
2017-09-06 07:42:13 +00:00
|
|
|
fxCache.trend = trend(fxCache.history, { 'avgPoints': 12 });
|
2017-08-18 14:08:28 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function updateFX() {
|
|
|
|
logger.warn('updateBitcoin');
|
2017-09-05 11:12:42 +00:00
|
|
|
|
2017-08-18 14:08:28 +00:00
|
|
|
const now = new Date();
|
2017-09-05 11:12:42 +00:00
|
|
|
|
|
|
|
if (now.getTime() > 1505696400000)
|
|
|
|
getFx();
|
|
|
|
|
2017-08-20 22:20:43 +00:00
|
|
|
const mod = delay - (now.getTime() % delay);
|
2017-08-18 14:08:28 +00:00
|
|
|
|
2017-09-06 07:42:13 +00:00
|
|
|
const fxUpdateFn = () => {
|
2017-08-18 14:08:28 +00:00
|
|
|
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
|
|
|
};
|