Skip to content

Commit

Permalink
Add pre hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Dec 12, 2014
1 parent 82df75e commit 2ffc356
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 10 deletions.
60 changes: 51 additions & 9 deletions index.js
Expand Up @@ -10,6 +10,8 @@ Kareem.prototype.execPre = function(name, context, callback) {
var numPres = pres.length;
var numAsyncPres = pres.numAsync || 0;
var currentPre = 0;
var asyncPresLeft = numAsyncPres;
var done = false;

if (!numPres) {
return process.nextTick(function() {
Expand All @@ -20,16 +22,56 @@ Kareem.prototype.execPre = function(name, context, callback) {
var next = function() {
var pre = pres[currentPre];

pre.fn.call(context, function(error) {
if (error) {
return callback(error);
}
if (++currentPre >= numPres) {
return callback();
}
if (pre.isAsync) {
pre.fn.call(
context,
function(error) {
if (error) {
if (done) {
return;
}
done = true;
return callback(error);
}

next();
});
++currentPre;
next();
},
function(error) {
if (error) {
if (done) {
return;
}
done = true;
return callback(error);
}

if (0 === --numAsyncPres) {
return callback();
}
});
} else {
pre.fn.call(context, function(error) {
if (error) {
if (done) {
return;
}
done = true;
return callback(error);
}

if (++currentPre >= numPres) {
if (asyncPresLeft > 0) {
// Leave parallel hooks to run
return;
} else {
return callback();
}
}

next();
});
}
};

next();
Expand Down
35 changes: 34 additions & 1 deletion test/examples.test.js
Expand Up @@ -60,12 +60,45 @@ describe('pre hooks', function() {
done();
});

var obj = { bacon: 0, eggs: 0 }
var obj = { bacon: 0, eggs: 0 };

hooks.execPre('cook', obj, function() {
assert.equal(3, obj.bacon);
assert.equal(4, obj.eggs);
done();
});
});

it('can execute parallel (async) pre hooks', function(done) {
hooks.pre('cook', true, function(next, done) {
this.bacon = 3;
next();
setTimeout(function() {
done();
}, 5);
});

hooks.pre('cook', true, function(next, done) {
next();
var _this = this;
setTimeout(function() {
_this.eggs = 4;
done();
}, 10);
});

hooks.pre('cook', function(next) {
this.waffles = false;
next();
});

var obj = { bacon: 0, eggs: 0 };

hooks.execPre('cook', obj, function() {
assert.equal(3, obj.bacon);
assert.equal(4, obj.eggs);
assert.equal(false, obj.waffles);
done();
});
});
});

0 comments on commit 2ffc356

Please sign in to comment.