Skip to content

Commit

Permalink
fix(urls): enable databases that are not hosted on domain root
Browse files Browse the repository at this point in the history
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 pouchdb-community#215
  • Loading branch information
ptitjes committed Jan 30, 2018
1 parent e977645 commit 6d879d6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
17 changes: 13 additions & 4 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ import inherits from 'inherits';
import { btoa } from 'pouchdb-binary-utils';

function getBaseUrl(db) {
// Parse database url
let url;
if (typeof db.getUrl === 'function') { // pouchdb pre-6.0.0
return urlParse(db.getUrl()).origin;
} else if (db.__opts && db.__opts.prefix) { // PouchDB.defaults
return db.__opts.prefix;
url = urlParse(db.getUrl());
} else { // pouchdb post-6.0.0
return urlParse(db.name).origin;
// Use PouchDB.defaults' prefix, if any
let prefix = db.__opts && db.__opts.prefix ? db.__opts.prefix + '/' : '';
url = urlParse(prefix + db.name);
}

// Compute parent path for databases not hosted on domain root (see #215)
let path = url.pathname;
path = path.endsWith('/') ? path.substring(0, -1) : path;
let parentPath = path.split('/').slice(0, -1).join('/');

return url.origin + parentPath;
}

function getConfigUrl(db, nodeName) {
Expand Down
11 changes: 7 additions & 4 deletions test/test.urls.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@ var PouchDB = require('pouchdb-memory');
var Authentication = require('../lib');
PouchDB.plugin(Authentication);

var utils = require('./test-utils');
var chai = require('chai');
chai.should();

var serverHost = utils.getConfig().serverHost;

describe('urls', function () {

var hostUrl = serverHost;
var hostUrl = 'http://example.com';
var dbName = 'testdb';
var dbUrl = hostUrl + '/' + dbName;

Expand Down Expand Up @@ -47,4 +44,10 @@ describe('urls', function () {
var usersUrl = db.getUsersDatabaseUrl();
usersUrl.should.equal(hostUrl + '/_users');
});

it('Correct users database url for proxied database urls (issue-215)', function () {
var db = new PouchDB(hostUrl + '/db/' + dbName);
var usersUrl = db.getUsersDatabaseUrl();
usersUrl.should.equal(hostUrl + '/db/_users');
});
});

0 comments on commit 6d879d6

Please sign in to comment.