Skip to content

Commit

Permalink
Merge pull request #36 from mongoosejs/vkarpov15/mongoose-12836
Browse files Browse the repository at this point in the history
avoid passing final callback to pre hook, because calling the callback can mess up hook execution
  • Loading branch information
vkarpov15 committed Jan 6, 2023
2 parents fd535fb + f7f95cd commit c6c77be
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 c6c77be

Please sign in to comment.