-
-
Save agaro1121/feaaff868480be2f7d7b2a7387f6a484 to your computer and use it in GitHub Desktop.
Superagent circuit breaker
This file contains 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") | |
, breaker = require("./breaker"); | |
// Add the circuit breaker to the default middleware | |
request.middleware.push(breaker(3000)); | |
// ...snip... | |
request | |
.get("/api") | |
.end(function(err, res){ | |
// This should get called since the server is under load | |
if(err) return console.error(err); | |
}); |
This file contains 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 | |
*/ | |
/** | |
* Disabling configuration | |
*/ | |
var globalTimeout | |
, disabled = false; | |
/** | |
* Circuit breaker middleware | |
* | |
* @return {Function} | |
* @api public | |
*/ | |
module.exports = function(timeout) { | |
return function(req, next) { | |
if(disabled) return next(new Error("Server unavailable")); | |
req.on('timeout', function(){ | |
disabled = true; | |
globalTimeout = setTimeout(function(){ | |
disabled = false; | |
}, timeout); | |
}); | |
next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment