有没有更好的方法在中间件中使用中间件?

时间:2014-01-30 21:03:32

标签: node.js express passport.js

例如,我想创建一些使用Passport的中间件,但我不想在使用此自定义中间件的应用程序中要求Passport。我相信我可以做到以下几点来实现这一目标。这是对的吗?有更好的方法吗?

someModule.js

var express = require('express'),
    passport = require('passport');

exports.someMiddleware = function(app) {
  app.use(passport.initialize());
  app.use(passport.session());
  return function(req, res, next) {
    // Do something
    next();
  }
}

app.js

var express = require('express');

var someModule = require('./someModule');

app = express();

app.use(someModule.someMiddleware(app))

而不是......

someModule.js

var express = require('express'),
    passport = require('passport');

exports.someMiddleware = function(app) {
  return function(req, res, next) {
    // Do something
    next();
  }
}

app.js

var express = require('express'),
    passport = require('passport');

var someModule = require('./someModule');

app = express();

app.use(passport.initialize());
app.use(passport.session());
app.use(someModule.someMiddleware())

1 个答案:

答案 0 :(得分:1)

我建议使用嵌入式应用程序来保持代码组织良好和可重用。保持嵌入式应用中的路由尽可能短,以便使用它们的主应用可以设置适当的基本路径。

module.js

var express = require('express');
var passport = require('passport');

var controller = module.exports = express();
controller.use(passport.initialize());
controller.use(passport.session());
// Login
controller.post('/', function (request, response, next) { /* ... */ });
// Logout
controller.del('/', function (request, response, next) { /* ... */ });

app.js

var app = express();
var controller = require('./controllers/module');

app.use('/authentication', controller);