Skip to content

Commit

Permalink
Closes #1, prevent next from being executed more than once.
Browse files Browse the repository at this point in the history
  • Loading branch information
elliotttf committed Aug 20, 2015
1 parent fed576b commit 4a20a44
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/conditional.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var once = require('once');

/**
* Returns a middleware that can be used to conditionally execute another
* middleware, or alternatively bypass it.
Expand Down Expand Up @@ -27,6 +29,7 @@
*/
module.exports = function (condition, middleware) {
return function (req, res, next) {
next = once(next);
if (condition === true || (typeof condition === 'function' && condition(req, res, next))) {
return middleware(req, res, next);
}
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,8 @@
"pre-commit": "gulp lint",
"pre-push": "gulp test"
}
},
"dependencies": {
"once": "^1.3.2"
}
}
25 changes: 25 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,31 @@ module.exports = {
test.ok(true, 'Conditional function returned false.');
test.done();
});
},

funcOnce: function (test) {
test.expect(2);

var count = 0;

var conditionFunc = function (req, res, next) {
next();
return true;
};

var middleware = conditional(
conditionFunc,
function (req, res, next) {
test.ok(true, 'Conditional executed.');
next();
test.done();
}
);

middleware({}, {}, function () {
count++;
test.equal(count, 1, 'Middleware only executed once.');
});
}
};

0 comments on commit 4a20a44

Please sign in to comment.