Skip to content

Commit b309db0

Browse files
Support URL-encoded socket names
1 parent 0ff40e7 commit b309db0

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

index.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,17 @@ function parse(str) {
4040
config.host = result.hostname;
4141
}
4242

43+
// If the host is missing it might be a URL-encoded path to a socket.
44+
var pathname = result.pathname;
45+
if (!config.host && pathname && pathname.toLowerCase().startsWith('%2f')) {
46+
var pathnameSplit = pathname.split('/');
47+
config.host = decodeURIComponent(pathnameSplit[0]);
48+
pathname = pathnameSplit.splice(1).join('/');
49+
}
4350
// result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls)
4451
// only strip the slash if it is present.
45-
var pathname = result.pathname;
4652
if (pathname && pathname.charAt(0) === '/') {
47-
pathname = result.pathname.slice(1) || null;
53+
pathname = pathname.slice(1) || null;
4854
}
4955
config.database = pathname && decodeURI(pathname);
5056

test/parse.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,30 @@ describe('parse', function(){
133133
subject.host.should.equal('/unix/socket');
134134
});
135135

136+
it('url with encoded socket', function() {
137+
var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname');
138+
subject.user.should.equal('user');
139+
subject.password.should.equal('pass');
140+
subject.host.should.equal('/unix/socket');
141+
subject.database.should.equal('dbname');
142+
});
143+
144+
it('url with real host and an encoded db name', function() {
145+
var subject = parse('pg://user:pass@localhost/%2Fdbname');
146+
subject.user.should.equal('user');
147+
subject.password.should.equal('pass');
148+
subject.host.should.equal('localhost');
149+
subject.database.should.equal('%2Fdbname');
150+
});
151+
152+
it('configuration parameter host treats encoded socket as part of the db name', function() {
153+
var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname?host=localhost');
154+
subject.user.should.equal('user');
155+
subject.password.should.equal('pass');
156+
subject.host.should.equal('localhost');
157+
subject.database.should.equal('%2Funix%2Fsocket/dbname');
158+
});
159+
136160
it('configuration parameter application_name', function(){
137161
var connectionString = 'pg:///?application_name=TheApp';
138162
var subject = parse(connectionString);

0 commit comments

Comments
 (0)