Created
October 11, 2012 05:12
-
-
Save lhitchon/3870307 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var connect = require('connect'), | |
mongodb = require('mongodb'); | |
var showDBInfo = function(req,res) { | |
res.end("You are connected to the database"); | |
}; | |
var noDatabaseError = function(res) { | |
res.statusCode = 500; | |
res.end("Unable to connect to database"); | |
} | |
var vcap_service_connect = function(service_type,req,res,next) { | |
var s = JSON.parse(process.env.VCAP_SERVICES)[service_type]; | |
if ( s == null || s.length < 1 ) { | |
noDatabaseError(res); | |
} else { | |
s = s[0]["credentials"]; | |
var server = new mongodb.Server( s["host"], s["port"]); | |
new mongodb.Db( s["db"], server, {} ).open( function(err,c) { | |
c.authenticate( s["username"], s["password"], function(err,client) { | |
if ( err ) { | |
noDatabaseError(res); | |
} else { | |
req.connection = connection = client; | |
next(); | |
} | |
}); | |
}); | |
} | |
} | |
var localhost_connect = function(name,req,res,next) { | |
var server = new mongodb.Server("127.0.0.1",27017,{}); | |
new mongodb.Db( name, server, {}).open( function(err,client) { | |
if ( err ) { | |
res.statusCode = 500; | |
res.end("Unable to connect to database"); | |
} else { | |
req.connection = connection = client; | |
next(); | |
} | |
}); | |
} | |
var dbConnection = function(name) { | |
var connection = null; | |
return function(req,res,next) { | |
if ( connection ) { | |
req.connection = connection; | |
next(); | |
} else { | |
if ( process.env.VCAP_SERVICES ) { | |
vcap_service_connect("mongodb-1.8",req,res,next); | |
} else { | |
localhost_connect(name,req,res,next); | |
} | |
} | |
} | |
} | |
var port = process.env.VCAP_APP_PORT || process.env.PORT || 3000; | |
connect.createServer( dbConnection("middleware-test"), showDBInfo).listen(port); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "db-middleware", | |
"version": "0.0.1", | |
"dependencies":{ | |
"connect":"1.8.3", | |
"mongodb":"0.9.7-2-2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment