From 165b7d7986b2184b2e4b73d33bf5803e61ce7a54 Mon Sep 17 00:00:00 2001 From: Spencer Alger Date: Fri, 7 Nov 2014 18:11:59 -0700 Subject: [PATCH] expand the url parsing ability of the Host class --- src/lib/host.js | 19 ++++++++++++++++--- test/unit/specs/host.js | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/lib/host.js b/src/lib/host.js index 768dfb8e2..921f6e212 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -9,6 +9,13 @@ var qs = require('querystring'); var _ = require('./utils'); var startsWithProtocolRE = /^([a-z]+:)?\/\//; +var defaultProto = 'http:'; + +/* jshint ignore:start */ +if (typeof window !== 'undefined') { + defaultProto = window.location.protocol; +} +/* jshint ignore:end */ var urlParseFields = [ 'protocol', 'hostname', 'pathname', 'port', 'auth', 'query' @@ -38,8 +45,12 @@ function Host(config, globalConfig) { this.suggestCompression = !!globalConfig.suggestCompression; if (typeof config === 'string') { - if (!startsWithProtocolRE.test(config)) { - config = 'http://' + config; + var firstColon = config.indexOf(':'); + var firstSlash = config.indexOf('/'); + var portWithPath = firstColon < firstSlash; + var portNoPath = firstColon > -1 && firstSlash === -1; + if ((portWithPath || portNoPath) && !startsWithProtocolRE.test(config)) { + config = defaultProto + '//' + config; } config = _.pick(url.parse(config, false, true), urlParseFields); // default logic for the port is to use 9200 for the default. When a string is specified though, @@ -72,7 +83,9 @@ function Host(config, globalConfig) { config = {}; } - _.assign(this, config); + _.forOwn(config, function (val, prop) { + if (val != null) this[prop] = val; + }, this); // make sure the query string is parsed if (this.query === null) { diff --git a/test/unit/specs/host.js b/test/unit/specs/host.js index 7bf22c7b5..28db76a8c 100644 --- a/test/unit/specs/host.js +++ b/test/unit/specs/host.js @@ -67,6 +67,29 @@ describe('Host class', function () { expect(host.port).to.be(9200); delete Host.defaultPorts.trift; }); + + it('parses simple urls properly', function () { + var host; + + host = new Host('elasticsearch'); + expect(host.path).to.be('/elasticsearch'); + + host = new Host('/elasticsearch'); + expect(host.path).to.be('/elasticsearch'); + + host = new Host('//localhost/elasticsearch'); + expect(host.host).to.be('localhost'); + expect(host.path).to.be('/elasticsearch'); + + host = new Host('localhost:9200'); + expect(host.host).to.be('localhost'); + expect(host.port).to.be(9200); + + host = new Host('localhost:9200/elasticsearch'); + expect(host.host).to.be('localhost'); + expect(host.port).to.be(9200); + expect(host.path).to.be('/elasticsearch'); + }); }); describe('based on the output from url.parse', function () {