From ac2e2b07a3460a0f15f366027465c2d05ff0f910 Mon Sep 17 00:00:00 2001 From: "Didier Villevalois (Ptitjes)" Date: Tue, 30 Jan 2018 23:45:57 +0100 Subject: [PATCH] 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 --- src/utils.js | 17 +++++++++++++---- test/test.urls.js | 11 +++++++---- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/utils.js b/src/utils.js index 603faa9..73da7a0 100644 --- a/src/utils.js +++ b/src/utils.js @@ -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.substr(-1, 1) === '/' ? path.substr(0, -1) : path; + let parentPath = path.split('/').slice(0, -1).join('/'); + + return url.origin + parentPath; } function getConfigUrl(db, nodeName) { diff --git a/test/test.urls.js b/test/test.urls.js index b7118f8..8929a00 100644 --- a/test/test.urls.js +++ b/test/test.urls.js @@ -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; @@ -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'); + }); });