var http = require('http'); var fxCache = {}; exports.doFx = function (req,res) { console.log('FX request'); function fxQuery(callback, r) { var req = r; var options = { host: 'openexchangerates.org', // port: 80, path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2', // method: 'GET', headers: { /* 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data)*/ } }; http.request(options).on('response', function (response) { var data = ''; response.on("data", function (chunk) { data += chunk; }); response.on('end', function () { callback(JSON.parse(data), r); }); }).end(); } var now = new Date(); if (now - GLOBAL.lastcheck > (60000 * 14)) { fxQuery(function (a, b) { console.log(a); fxCache = a; GLOBAL.lastcheck = now; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(fxCache)); }, res); } else { console.log("Using cache"); res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(fxCache)); } };