diff --git a/index.js b/index.js index afb36996..b041a208 100644 --- a/index.js +++ b/index.js @@ -36,7 +36,15 @@ function parse(str) { return config; } config.host = result.hostname; - config.database = result.pathname ? decodeURI(result.pathname.slice(1)) : null; + + // result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls) + // only strip the slash if it is present. + var pathname = result.pathname; + if (pathname && pathname.charAt(0) === '/') { + pathname = result.pathname.slice(1) || null; + } + config.database = pathname && decodeURI(pathname); + var auth = (result.auth || ':').split(':'); config.user = auth[0]; config.password = auth[1]; diff --git a/test/parse.js b/test/parse.js index 1b9b203c..89269429 100644 --- a/test/parse.js +++ b/test/parse.js @@ -87,3 +87,26 @@ test('url is properly encoded', function(t){ t.equal(subject.database, ' u%20rl'); t.end(); }); + +test('relative url sets database', function(t){ + var relative = 'different_db_on_default_host'; + var subject = parse(relative); + t.equal(subject.database, 'different_db_on_default_host'); + t.end(); +}); + +test('no pathname returns null database', function (t) { + var subject = parse('pg://myhost'); + t.equal(subject.host, 'myhost'); + t.type(subject.database, 'null'); + + t.end(); +}); + +test('pathname of "/" returns null database', function (t) { + var subject = parse('pg://myhost/'); + t.equal(subject.host, 'myhost'); + t.type(subject.database, 'null'); + + t.end(); +});