Skip to content

Commit

Permalink
feat: Make actions flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
lance committed Nov 1, 2016
1 parent c72d364 commit 2672c34
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const fallbackFunction = Symbol('fallback');

class CircuitBreaker {
constructor (action, options) {
this.action = action;
if (typeof action !== 'function') this.action = () => action;
else this.action = action;
this.options = options;
this.status = new Status();
this.Promise = options.Promise;
Expand All @@ -35,8 +36,10 @@ class CircuitBreaker {
}

fire () {
const args = Array.prototype.slice.call(arguments);

if (this.open || (this.halfOpen && this[halfOpenAttempted])) {
return failFast(this, Array.prototype.slice.call(arguments));
return failFast(this, args);
}

this[halfOpenAttempted] = this.halfOpen;
Expand All @@ -47,7 +50,7 @@ class CircuitBreaker {
},
this.options.timeout);

this.action.apply(this.action, arguments)
this.Promise.resolve(this.action.apply(this.action, args))
.then((result) => {
succeed(this);
resolve(result);
Expand Down
34 changes: 34 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,33 @@ test('Passes arguments to the circuit function', (t) => {
.catch(t.fail);
});

test('Works with functions that do not return a promise', (t) => {
const breaker = circuitBreaker(nonPromise);

breaker.fire()
.then((arg) => t.equals(arg, 'foo'))
.then(t.end)
.catch(t.fail);
});

test('Works with non-functions', (t) => {
const breaker = circuitBreaker('foobar');

breaker.fire()
.then((arg) => t.equals(arg, 'foobar'))
.then(t.end)
.catch(t.fail);
});

test.skip('Works with callback functions', (t) => {
const breaker = circuitBreaker(callbackFunction);

breaker.fire(3, 4)
.then((arg) => t.equals(arg, 7))
.then(t.end)
.catch(t.fail);
});

test('Fails when the circuit function fails', (t) => {
const expected = -1;
const breaker = circuitBreaker(passFail);
Expand Down Expand Up @@ -136,3 +163,10 @@ function slowFunction () {
});
}

function nonPromise () {
return 'foo';
}

function callbackFunction (x, y, callback) {
callback(x + y);
}

0 comments on commit 2672c34

Please sign in to comment.