From 64245348315f1b8602a9fca9a6cca86b0ea180b3 Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Thu, 1 Jan 2015 17:57:09 +0800 Subject: [PATCH] executor: pass correct `this` to middleware Fix the bug "can't configure passport#initialize in middleware.json" --- lib/executor.js | 2 +- test/executor.test.js | 23 +++++++++++++++++++++++ test/fixtures/passport.js | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/passport.js diff --git a/lib/executor.js b/lib/executor.js index cfbf69a..a0d322a 100644 --- a/lib/executor.js +++ b/lib/executor.js @@ -280,7 +280,7 @@ function setupMiddleware(app, instructions) { data.fragment ? ('#' + data.fragment) : ''); var factory = require(data.sourceFile); if (data.fragment) { - factory = factory[data.fragment]; + factory = factory[data.fragment].bind(factory); } assert(typeof factory === 'function', 'Middleware factory must be a function'); diff --git a/test/executor.test.js b/test/executor.test.js index 8fd6f86..bd17481 100644 --- a/test/executor.test.js +++ b/test/executor.test.js @@ -467,6 +467,29 @@ describe('executor', function() { expect(app.componentOptions).to.eql({ option: 'value' }); }); + + it('configures middleware (that requires `this`)', function(done) { + var passportPath = require.resolve('./fixtures/passport'); + + boot.execute(app, someInstructions({ + middleware: { + phases: ['auth'], + middleware: [ + { + sourceFile: passportPath, + fragment: 'initialize', + config: { + phase: 'auth:before' + } + } + ] + } + })); + + supertest(app) + .get('/') + .expect('passport', 'initialized', done); + }); }); function assertValidDataSource(dataSource) { diff --git a/test/fixtures/passport.js b/test/fixtures/passport.js new file mode 100644 index 0000000..3dd8c13 --- /dev/null +++ b/test/fixtures/passport.js @@ -0,0 +1,19 @@ +var framework = { + initialize: function(passport) { + return function(req, res, next) { + req._passport = passport; + res.setHeader('passport', 'initialized'); + next(); + }; + } +}; + +var Passport = function() { + this._framework = framework; +}; + +Passport.prototype.initialize = function() { + return this._framework.initialize(this); +}; + +module.exports = new Passport();