Skip to content

Instantly share code, notes, and snippets.

@webjay
Last active August 29, 2015 14:17
Show Gist options
  • Save webjay/6d65c0abb2a27a45df0e to your computer and use it in GitHub Desktop.
Save webjay/6d65c0abb2a27a45df0e to your computer and use it in GitHub Desktop.
Functional wrapHandler
'use strict';
function wrapHandler (handler, callback) {
var name = arguments[0].name || 'clone';
return function (err) {
if (err) return callback(err);
console.log(name, 'called with', arguments);
var args = Array.prototype.slice.call(arguments, 1);
args.push(callback);
handler.apply(this, args);
};
}
describe('Functional', function () {
it('passes 1 method', function (done) {
// methods
function fn1 (msg, callback) {
callback();
}
// wrap
var w1 = wrapHandler(fn1, done);
// call
w1(null, 'hello');
});
it('passes 2 methods', function (done) {
// methods
function fn1 (msg, callback) {
callback();
}
function fn2 (callback) {
callback();
}
// wrap
var w1 = wrapHandler(fn1, wrapHandler(fn2, done));
// call
w1(null, 'hello');
});
it('passes 3 methods', function (done) {
// methods
function fn1 (msg, callback) {
callback(null, msg + '.');
}
var fn2 = fn1.bind({});
function fn3 (msg, callback) {
callback(null, msg);
}
// wrap
var w1 = wrapHandler(fn1, wrapHandler(fn2, wrapHandler(fn3, function (err, msg) {
(!err).should.be.true;
msg.should.equal('hello..');
done(err);
})));
// call
w1(null, 'hello');
});
it('passes err to 2nd, thus skips 2nd and 3rd method', function (done) {
// methods
function fn1 (msg, callback) {
callback('bad msg');
}
var fn2 = fn1.bind({});
function fn3 (msg, callback) {
console.log('please do not call me');
callback();
}
// wrap
var w1 = wrapHandler(fn1, wrapHandler(fn2, wrapHandler(fn3, function (err) {
(!!err).should.be.true;
done();
})));
// call
w1(null, 'hello');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment