Created
February 3, 2013 05:36
-
-
Save camshaft/4700655 to your computer and use it in GitHub Desktop.
Superagent cache middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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