在expressjs中设置请求清理中间件

mar*_*ark 5 connect node.js express

我正在尝试使用postgresql作为后端编写一个expressjs服务器.每个请求都通过调用pg.connect以获取池连接(client)以及在不再需要连接后将其返回池中的方法开始(done).例如:

  function dbConnect(req, res, next) {
    if (res.locals.pgCtx) {
      next();
      return;
    }

    pg.connect(dbConn, function (err, client, done) {
      if (err) {
        res.send(500, err.message);
      } else {
        app.locals.pgCtx = res.locals.pgCtx = {
          client: client,
          done: done
        };
        next();
      }
    });
  }

  app.use(allowCrossDomain);
  app.use(express.methodOverride());
  app.use(express.compress());
  app.use(express.bodyParser());
  app.use(express.logger());
  app.use(passport.initialize());
  app.use(express["static"](webRootDir));
  app.use(dbConnect);                       // <--------------
  app.use(authenticate);
  app.use(app.router);
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('view engine', 'jade');
  app.set('views', webRootDir);
  app.engine("jade", jade.__express);

  indexHandlers = [fetchConstData, function (req, res) {
    res.render(templatesDir + 'index', {
      constData: app.locals.constData,
      env: app.get('env'),
      user: req.user,
      admin: isAdmin(req.user.role),
      host: req.host
    });
  }];
  app.get('/', indexHandlers);
  app.get('/index', indexHandlers);
  app.get('/index.html', indexHandlers);
Run Code Online (Sandbox Code Playgroud)

我的问题是,虽然我可以插入dbConnect作为全局中间件在任何其他中间件之前运行请求,但我还需要能够在运行所有中间件后进行清理,以便将连接返回到池中.

理想情况下,无论请求如何结束,都应该有一种方法来指定在运行所有特定于请求的中间件之后运行的全局中间件 - 通过:

  • res.send(...)
  • 抛出一个例外
  • 将错误的对象传递给 next()

请注意,任何特定于请求的中间件都可以通过这种方式终止链.

现在我只能看到这种方法:

  1. 通过注册自定义全局错误处理程序中间件而不是注意到负面结果express.errorHandler.
  2. 通过自定义版本替换对象中的res.send方法,该res版本首先将连接返回池,然后继续res.send执行原始实现.

所有这一切都有强烈的黑客气味.我想做得对,所以我想问有没有办法注册像请求清理中间件?

编辑

必须将静态内容处理程序移到dbConnect中间件之上,否则我们会泄漏数据库连接,直到没有更多连接可用,并且服务器无法提供任何服务,因为dbConnect永远不会返回等待连接被释放.

rob*_*lep 12

有一个finish事件可以监听响应对象,并在响应完成时发出:

function dbConnect(req, res, next) {
  res.on('finish', function() {
    // perform your cleanups...
  });
  ...
}
Run Code Online (Sandbox Code Playgroud)