expand the url parsing ability of the Host class

This commit is contained in:
Spencer Alger
2014-11-07 18:11:59 -07:00
parent 12dec0849d
commit 165b7d7986
2 changed files with 39 additions and 3 deletions

View File

@ -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) {

View File

@ -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 () {