Skip to content

Commit

Permalink
avoid passing final callback to pre hook, because calling the callbac…
Browse files Browse the repository at this point in the history
…k can mess up hook execution

Fix Automattic/mongoose#12836
  • Loading branch information
vkarpov15 committed Jan 2, 2023
1 parent fd535fb commit f7f95cd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions index.js
Expand Up @@ -84,6 +84,9 @@ Kareem.prototype.execPre = function(name, context, args, callback) {
const args = [decorateNextFn(_next)];
const _args = arguments.length >= 2 ? arguments : [null].concat($args);
for (let i = 1; i < _args.length; ++i) {
if (i === _args.length - 1 && typeof _args[i] === 'function') {
continue; // skip callbacks to avoid accidentally calling the callback from a hook
}
args.push(_args[i]);
}

Expand Down
35 changes: 35 additions & 0 deletions test/pre.test.js
Expand Up @@ -289,6 +289,41 @@ describe('execPre', function() {
});
});

it('avoids passing final callback to pre', function(done) {
const execed = {};

hooks.pre('cook', function(next) {
execed.first = true;
assert.equal(arguments.length, 1);
next(null, 'test');
});

hooks.pre('cook', function(next, p, _cb) {
execed.second = true;
assert.equal(p, 'test');
assert.equal(arguments.length, 2);
next();
});

hooks.pre('cook', function(next, p) {
execed.third = true;
assert.ok(!p);
assert.equal(arguments.length, 1);
next();
});

hooks.execPre('cook', null, [finalCb], function(err) {
assert.ifError(err);
assert.equal(3, Object.keys(execed).length);
assert.ok(execed.first);
assert.ok(execed.second);
assert.ok(execed.third);
done();
});

function finalCb() {}
});

it('handles sync errors in pre if there are more hooks', function(done) {
const execed = {};

Expand Down

0 comments on commit f7f95cd

Please sign in to comment.