Skip to content

Commit

Permalink
Post hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Dec 12, 2014
1 parent 1cc1b9f commit 395b67c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 9 deletions.
44 changes: 35 additions & 9 deletions index.js
Expand Up @@ -90,16 +90,48 @@ Kareem.prototype.execPre = function(name, context, callback) {
next();
};

Kareem.prototype.execPost = function(name, context, callback) {
Kareem.prototype.execPost = function(name, context, args, callback) {
var posts = this._posts[name] || [];
var numPosts = posts.length;
var currentPost = 0;
var done = false;

if (!numPres) {
if (!numPosts) {
return process.nextTick(function() {
callback();
});
}

var next = function() {
var post = posts[currentPost];

if (post.length > args.length) {
post.apply(context, args.concat(function(error) {
if (error) {
if (done) {
return;
}
return callback(error);
}

if (++currentPost >= numPosts) {
return callback.apply(null, [undefined].concat(args));
}

next();
}));
} else {
post.apply(context, args);

if (++currentPost >= numPosts) {
return callback.apply(null, [undefined].concat(args));
}

next();
}
};

next();
};

Kareem.prototype.pre = function(name, isAsync, fn, error) {
Expand All @@ -122,13 +154,7 @@ Kareem.prototype.pre = function(name, isAsync, fn, error) {
return this;
};

Kareem.prototype.post = function(name, isAsync, fn) {
if (arguments.length === 2) {
fn = isAsync;
isAsync = false;
}

fn.isAsync = isAsync;
Kareem.prototype.post = function(name, fn) {
(this._posts[name] = this._posts[name] || []).push(fn);
return this;
};
Expand Down
29 changes: 29 additions & 0 deletions test/examples.test.js
Expand Up @@ -120,4 +120,33 @@ describe('pre hooks', function() {
done();
});
});
});

describe('post hooks', function() {
var hooks;

beforeEach(function() {
hooks = new Kareem();
});

it('runs without any hooks specified', function(done) {
hooks.execPost('cook', null, [], function() {
done();
});
});

it('executes with parameters passed in', function(done) {
hooks.post('cook', function(eggs, bacon, callback) {
assert.equal(1, eggs);
assert.equal(2, bacon);
callback();
});

hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) {
assert.ifError(error);
assert.equal(1, eggs);
assert.equal(2, bacon);
done();
});
});
});

0 comments on commit 395b67c

Please sign in to comment.