Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Last active August 29, 2015 13:57
Show Gist options
  • Save dlmanning/9755065 to your computer and use it in GitHub Desktop.
Save dlmanning/9755065 to your computer and use it in GitHub Desktop.
simple api proxy that queues requests when cached data is out of date.
var request = require('request');
var moment = require('moment');
var http = require('http');
var colors = require('colors');
var latLong = "45.5330,-122.6894";
var apiKey = "a75c248d7b83806b66b281dd33e96e36";
var url = 'https://api.forecast.io/forecast';
url += '/' + apiKey + '/' + latLong;
request(url, function (err, apiResponse, body) {
var appData = {};
appData.data = JSON.parse(body);
appData.timeStamp = Date.now();
serverReady(appData);
});
function serverReady (appData) {
var queueRequest = requestQueue(appData);
http.createServer(function (clientRequest, myResponse) {
if (Date.now() - appData.timeStamp > 10000) {
console.log(timeStamp('yellow') + ' - Queueing request from: ' + clientRequest.headers.host);
queueRequest(function (body) {
console.log(timeStamp('red') + ' - Answering queued request from: ' + clientRequest.headers.host);
myResponse.end(body);
});
} else {
console.log(timeStamp('green') + ' - Request from: ' + clientRequest.headers.host);
myResponse.end(JSON.stringify(appData.data));
}
}).listen(7357);
console.log('Listening on: 7357');
}
function timeStamp (color) {
return ('[' + moment(Date.now()).format('hh:mm:ssa') + ']')[color];
}
function requestQueue (appData) {
var itsOnItsWay = false;
var callbacks = [];
return function (cb) {
callbacks.push(cb);
if (!itsOnItsWay) {
request(url, function (err, apiResponse, body) {
appData.data = JSON.parse(body);
appData.timeStamp = Date.now();
callbacks.forEach(function (cb) {
cb(body);
});
itsOnItsWay = false;
callbacks = [];
});
itsOnItsWay = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment