我正在尝试使用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);
我的问题是,虽然我可以插入dbConnect
作为要在任何其他中间件之前运行的全局中间件,但我还需要能够在运行所有中间件后进行清理才能返回连接回到游泳池。
理想情况下,无论请求如何结束,应该有一种方法可以指定在运行所有特定于请求的中间件后运行的全局中间件 - 无论是通过:
res.send(...)
next()
请注意,任何特定于请求的中间件都可以通过这种方式终止链。
现在我只能看到这种方法:
express.errorHandler
来加入否定结果。res.send
对象中的res
方法替换为首先将连接返回池的自定义版本,然后继续执行原始res.send
实现。所有这一切都有强烈的黑客气味。我想做得对,所以我想问有没有办法注册类似请求清理中间件?
修改
静态内容处理程序必须移到dbConnect
中间件之上,否则我们会泄漏数据库连接,直到没有更多连接可用且服务器无法提供任何服务,因为dbConnect
永远不会返回等待连接被释放。
答案 0 :(得分:12)
您可以在响应对象上侦听finish
事件,并在响应完成时发出该事件:
function dbConnect(req, res, next) {
res.on('finish', function() {
// perform your cleanups...
});
...
}