Skip to content

Instantly share code, notes, and snippets.

@zzen
Created March 9, 2012 19:38
Show Gist options
  • Save zzen/2008270 to your computer and use it in GitHub Desktop.
Save zzen/2008270 to your computer and use it in GitHub Desktop.
Memoize requests
var http = require('http'), EventEmitter = require('events').EventEmitter;
var cache = {};
http.createServer(function (req, res) {
var key = someMagic(req), cached = cache[key]; // get some unique request identifier
if (!cached) { // if we've never seen this request before
cached = new EventEmitter(); // make this cache entry an event emitter
cached.status = 'running';
handleAsyncRequest(function(result) { // your request handling is probably asynchronous, call this callback when you're done
cached.response = result; // memoize data
cached.status = 'finished';
cached.emit('finished'); // notify all observers waiting for this request
});
} else {
switch(cached.status) { // if existing request, check if it's still running or finished
case 'finished':
res.end(cached.response); // send cached response immediately if request has finished
break;
case 'running':
// subscribe as observer; send response when request is finished
cached.once('finished', function() { res.end(cached.response); });
break;
}
}
}).listen(1337, "127.0.0.1");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment