db.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* vim: set ts=2: */
  2. var url = require( 'url' );
  3. var mongo = require( 'mongodb' );
  4. module.exports.open = function( uri, callback ) {
  5. if( ! uri ) {
  6. throw new Error( 'No URI defined!' );
  7. }
  8. var parsed = url.parse( uri );
  9. var path = parsed.pathname.split( '/' );
  10. var port = parsed.port || 27017;
  11. var host = parsed.hostname || 'localhost';
  12. var db = path[ 1 ];
  13. var collection = path[ 2 ];
  14. if( parsed.auth ) {
  15. var auth = parsed.auth.split( ':' );
  16. var username = auth[ 0 ];
  17. var password = auth[ 1 ];
  18. }
  19. if( ! db ) {
  20. throw new Error( 'Unable to parse database name!' );
  21. }
  22. var server = new mongo.Server( host, port, { auto_reconnect : true } );
  23. var database = new mongo.Db( db, server );
  24. database.open( function( err, database ) {
  25. // XXX: add authentication
  26. if( err ) {
  27. callback( err );
  28. } else {
  29. // do we want to open a specific collection? otherwise just return DB
  30. if( ! collection ) {
  31. callback( null, database );
  32. } else {
  33. database.createCollection( collection, function( err, c ) {
  34. if( err ) {
  35. callback( err );
  36. } else {
  37. callback( null, c );
  38. }
  39. });
  40. }
  41. }
  42. });
  43. }