2017-09-25 19:40:22 +08:00
|
|
|
const _ = require('underscore');
|
|
|
|
|
|
|
|
module.exports = function dbConnSetupMiddleware(pgConnection) {
|
2017-10-06 00:05:46 +08:00
|
|
|
return function dbConnSetup(req, res, next) {
|
2017-10-03 23:47:57 +08:00
|
|
|
const user = res.locals.user;
|
2017-09-25 19:40:22 +08:00
|
|
|
|
2017-09-29 17:07:11 +08:00
|
|
|
pgConnection.setDBConn(user, res.locals, (err) => {
|
2017-09-25 19:40:22 +08:00
|
|
|
if (err) {
|
|
|
|
if (err.message && -1 !== err.message.indexOf('name not found')) {
|
|
|
|
err.http_status = 404;
|
|
|
|
}
|
|
|
|
req.profiler.done('req2params');
|
2017-10-05 23:28:41 +08:00
|
|
|
return next(err);
|
2017-09-25 19:40:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add default database connection parameters
|
|
|
|
// if none given
|
2017-09-29 17:07:11 +08:00
|
|
|
_.defaults(res.locals, {
|
2017-09-25 19:40:22 +08:00
|
|
|
dbuser: global.environment.postgres.user,
|
|
|
|
dbpassword: global.environment.postgres.password,
|
|
|
|
dbhost: global.environment.postgres.host,
|
|
|
|
dbport: global.environment.postgres.port
|
|
|
|
});
|
|
|
|
|
2017-10-06 00:05:46 +08:00
|
|
|
res.set('X-Served-By-DB-Host', req.params.dbhost);
|
|
|
|
|
2017-09-25 19:40:22 +08:00
|
|
|
req.profiler.done('req2params');
|
|
|
|
|
2017-10-05 23:28:41 +08:00
|
|
|
next(null);
|
2017-09-25 19:40:22 +08:00
|
|
|
});
|
|
|
|
};
|
|
|
|
};
|