Skip to content

Commit ac2e2b0

Browse files
committed
fix(urls): enable databases that are not hosted on domain root
Databases can be proxied (nginx, express-pouch, ...) and be hosted in a sub-path of a domain. This was not taken in account during the refactoring to use url-parse (commit 7472135). Fixes #215
1 parent e977645 commit ac2e2b0

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

src/utils.js

+13-4
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,22 @@ import inherits from 'inherits';
66
import { btoa } from 'pouchdb-binary-utils';
77

88
function getBaseUrl(db) {
9+
// Parse database url
10+
let url;
911
if (typeof db.getUrl === 'function') { // pouchdb pre-6.0.0
10-
return urlParse(db.getUrl()).origin;
11-
} else if (db.__opts && db.__opts.prefix) { // PouchDB.defaults
12-
return db.__opts.prefix;
12+
url = urlParse(db.getUrl());
1313
} else { // pouchdb post-6.0.0
14-
return urlParse(db.name).origin;
14+
// Use PouchDB.defaults' prefix, if any
15+
let prefix = db.__opts && db.__opts.prefix ? db.__opts.prefix + '/' : '';
16+
url = urlParse(prefix + db.name);
1517
}
18+
19+
// Compute parent path for databases not hosted on domain root (see #215)
20+
let path = url.pathname;
21+
path = path.substr(-1, 1) === '/' ? path.substr(0, -1) : path;
22+
let parentPath = path.split('/').slice(0, -1).join('/');
23+
24+
return url.origin + parentPath;
1625
}
1726

1827
function getConfigUrl(db, nodeName) {

test/test.urls.js

+7-4
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,12 @@ var PouchDB = require('pouchdb-memory');
44
var Authentication = require('../lib');
55
PouchDB.plugin(Authentication);
66

7-
var utils = require('./test-utils');
87
var chai = require('chai');
98
chai.should();
109

11-
var serverHost = utils.getConfig().serverHost;
12-
1310
describe('urls', function () {
1411

15-
var hostUrl = serverHost;
12+
var hostUrl = 'http://example.com';
1613
var dbName = 'testdb';
1714
var dbUrl = hostUrl + '/' + dbName;
1815

@@ -47,4 +44,10 @@ describe('urls', function () {
4744
var usersUrl = db.getUsersDatabaseUrl();
4845
usersUrl.should.equal(hostUrl + '/_users');
4946
});
47+
48+
it('Correct users database url for proxied database urls (issue-215)', function () {
49+
var db = new PouchDB(hostUrl + '/db/' + dbName);
50+
var usersUrl = db.getUsersDatabaseUrl();
51+
usersUrl.should.equal(hostUrl + '/db/_users');
52+
});
5053
});

0 commit comments

Comments
 (0)