Skip to content

Instantly share code, notes, and snippets.

@graimon
Created April 19, 2018 15:11
Show Gist options
  • Select an option

  • Save graimon/ea108aa3bfdd17b119c71ac0e4deff87 to your computer and use it in GitHub Desktop.

Select an option

Save graimon/ea108aa3bfdd17b119c71ac0e4deff87 to your computer and use it in GitHub Desktop.
Sample Node app using knex.js with postgres. Used to test the active connections on an Azure Web App.
//set DEBUG=knex* to get more info
let activeConnections = 0;
const knexSettings = {
client: 'pg',
pool: {
min: 2,
max: 10,
afterCreate: function (conn, done) {
console.log(`New DB Connection! active connections: ${++activeConnections}`);
done(null, conn);
},
beforeDestroy: function (conn, done) {
console.log(`DB Connection Released! active connections: ${--activeConnections}`);
done(null, conn);
},
},
connection: 'postgres://localhost/some_db'//process.env.POSTGRESQLCONNSTR_DB
}
const port = 3000; //process.env.PORT
const knex = require('knex')(knexSettings);
const healthcheck = require('healthcheck-middleware')({
addChecks: function(fail, pass) {
knex.raw('SELECT 1=1;')
.then(function() {
console.log('query was successful');
pass();
})
.catch(function(err) {
console.error('query wasn\'t successful');
console.error(err);
fail(new Error('could not connect to database'));
})
}
});
const server = require('express')();
server.use('/', healthcheck);
server.listen(port);
console.log(`Server running on port ${port}`);
{
"name": "knex-postgres-sample",
"version": "0.0.1",
"description": "",
"main": "app.js",
"engines": {
"node": "8.4.0",
"npm": "4.2.0"
},
"dependencies": {
"express": "^4.12.3",
"healthcheck-middleware": "^1.0.1",
"knex": "^0.14.6",
"pg": "^7.4.1"
},
"devDependencies": {},
"scripts": {
"start": "node app.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment