Skip to content

Instantly share code, notes, and snippets.

@agaro1121
Forked from camshaft/app.js
Created October 7, 2018 22:49
Show Gist options
  • Save agaro1121/feaaff868480be2f7d7b2a7387f6a484 to your computer and use it in GitHub Desktop.
Save agaro1121/feaaff868480be2f7d7b2a7387f6a484 to your computer and use it in GitHub Desktop.
Superagent circuit breaker
/**
* 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);
});
/**
* 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