Skip to content

Instantly share code, notes, and snippets.

@mschultheiss83
Created January 29, 2016 22:11
Show Gist options
  • Save mschultheiss83/85058f5d48b989901c6a to your computer and use it in GitHub Desktop.
Save mschultheiss83/85058f5d48b989901c6a to your computer and use it in GitHub Desktop.
a middleware file for restify to use knex as database connection
/**
* Created by m.schultheiss on 29.01.2016.
* References:
* - http://restify.com/
* - http://knexjs.org/
* Helpers:
* - https://github.com/trentm/node-bunyan
* - https://lodash.com
*/
var knex = require("knex"),
dbManager = require("../../config/databases"),
_ = require("lodash");
function closeKnex(option) {
//try to knex.destroy
option.knex && option.knex.destroy && option.knex.destroy(function onDestroy() {
// on success log closed connection
if (option.log && option.log.info) {
option.log.info({
"note": "DB connection closed",
"origin": "mcp-database",
"customer": option.customer,
"dbConfig": option.dbConfig,
"event": "closeConnection"
});
} else {
console.log("DB connection closed", {
"customer": option.customer,
"dbConfig": option.dbConfig
})
}
});
}
exports = function(req, res, next) {
// load config via header
req.dbConfig = dbManager.findCustomerDB(req.headers["x-api-customers"] || req.params.customers);
// set req.knex for later usage
req.knex = knex(req.dbConfig);
//create transport object
var option = {
"customer": req.headers["x-api-customers"] || req.params.customers,
"dbConfig": req.dbConfig,
"knex": req.knex
};
// dumping dbConfig as openConnection event, @see http://restify.com/#audit-logging
req.log.info(_.merge(option, {
"event": "openConnection"
}), "db connection opened");
// close connection once response is send
res.once("finish", closeKnex.bind(this, _.merge(option, {
"log": req.log
})));
// call to run next route
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment