diff --git a/lib/middleware/rest.js b/lib/middleware/rest.js index 37bf785c..71c98154 100644 --- a/lib/middleware/rest.js +++ b/lib/middleware/rest.js @@ -22,33 +22,31 @@ module.exports = rest; * @header loopback.rest() */ -function rest(options) { - options = options || {}; - var tokenParser = null; - var contextHandler = null; - if (options.context) { - var contextOptions = options.context; - if(typeof contextOptions !== 'object') { - contextOptions = {}; - } - contextHandler = loopback.context(contextOptions); - } +function rest() { return function restApiHandler(req, res, next) { var app = req.app; - var handler = app.handler('rest'); + var restHandler = app.handler('rest'); if (req.url === '/routes') { - return res.send(handler.adapter.allRoutes()); + return res.send(restHandler.adapter.allRoutes()); } else if (req.url === '/models') { return res.send(app.remotes().toJSON()); } - var handlers = []; - if (options.context) { - handlers.push(contextHandler); - } - if (app.isAuthEnabled) { - if (!tokenParser) { + var preHandlers; + + if (!preHandlers) { + preHandlers = []; + var remotingOptions = app.get('remoting') || {}; + + var contextOptions = remotingOptions.context; + if (contextOptions !== false) { + if (typeof contextOptions !== 'object') + contextOptions = {}; + preHandlers.push(loopback.context(contextOptions)); + } + + if (app.isAuthEnabled) { // NOTE(bajtos) It would be better to search app.models for a model // of type AccessToken instead of searching all loopback models. // Unfortunately that's not supported now. @@ -56,12 +54,11 @@ function rest(options) { // https://github.com/strongloop/loopback/pull/167 // https://github.com/strongloop/loopback/commit/f07446a var AccessToken = loopback.getModelByType(loopback.AccessToken); - tokenParser = loopback.token({ model: AccessToken }); - handlers.push(tokenParser); + preHandlers.push(loopback.token({ model: AccessToken })); } } - handlers.push(handler); - async.eachSeries(handlers, function(handler, done) { + + async.eachSeries(preHandlers.concat(restHandler), function(handler, done) { handler(req, res, done); }, next); }; diff --git a/test/rest.middleware.test.js b/test/rest.middleware.test.js index 1ddaf50b..89877af7 100644 --- a/test/rest.middleware.test.js +++ b/test/rest.middleware.test.js @@ -178,7 +178,7 @@ describe('loopback.rest', function() { } it('should enable context using loopback.context', function(done) { - app.use(loopback.context({enableHttpContext: true})); + app.use(loopback.context({ enableHttpContext: true })); app.enableAuth(); app.use(loopback.rest()); @@ -187,7 +187,8 @@ describe('loopback.rest', function() { it('should enable context with loopback.rest', function(done) { app.enableAuth(); - app.use(loopback.rest({context: {enableHttpContext: true}})); + app.set('remoting', { context: { enableHttpContext: true } }); + app.use(loopback.rest()); invokeGetToken(done); });