Skip to content

Instantly share code, notes, and snippets.

@camshaft
Created February 3, 2013 05:36
Show Gist options
  • Save camshaft/4700655 to your computer and use it in GitHub Desktop.
Save camshaft/4700655 to your computer and use it in GitHub Desktop.
Superagent cache middleware
/**
* Module dependencies
*/
var request = require("superagent")
, cache = require("./cache");
// Add the cache to the default middleware
request.middleware.push(cache());
request
.get("/api")
.end(function(err, res){
// Should hit the server
console.log(res.body);
request
.get("/api")
.end(function(err, res){
// Should not hit the server but still return the same response
console.log(res.body);
});
});
/**
* Module dependencies
*/
/**
* Cache
*/
var cache = {};
/**
* Cache middleware
*
* @return {Function}
* @api public
*/
module.exports = function() {
return function(req, next) {
if(cache[req.url]) {
req.emit("response", cache[req.url]);
return req.emit("end");
}
next(null, function(res, prev){
if(res.ok) {
cache[req.url] = res;
}
prev();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment