Skip to content

Commit

Permalink
Adds support for batching requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
johncoder committed Jul 31, 2014
1 parent f879941 commit c772b6f
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,54 @@ var cachestore = new Eidetic({
canPutWhenFull: true
});

var queues = {};

module.exports.cacheSeconds = function(ttl) {

return function(req, res, next) {

var self = this;
var cache = cachestore.get(req.path);
//var send = res.send;
res.original_send = res.send;

// returns the value immediately
if (cache) {
res.send(cache);
} else {
var send = res.send;
res.send = function(string) {
return;
}

if (!queues[req.path]) {
queues[req.path] = [];
}

// first request will get rendered output
if (queues[req.path].length === 0
&& queues[req.path].push(function noop(){})) {

res.send = function (string) {
var body = string instanceof Buffer ? string.toString() : string;
cachestore.put(req.url, body, ttl);
send.call(this, body);

// drain the queue so anyone else waiting for
// this value will get their responses.
var subscriber = null;
while (subscriber = queues[req.path].shift()) {
if (subscriber) {
process.nextTick(subscriber);
}
}
res.original_send(body);
};

next();
// subsequent requests will batch while the first computes
} else {
queues[req.path].push(function() {
var body = cachestore.get(req.path);
res.send(body);
});
}

}

};

0 comments on commit c772b6f

Please sign in to comment.