Better and tested fixUrl().

This commit is contained in:
Julien Fontanet 2015-02-05 12:41:25 +01:00
parent debcf086b5
commit f93f115e13
3 changed files with 51 additions and 22 deletions

View File

@ -15,30 +15,17 @@ function notConnected() {
}
// Fix URL if necessary.
var URL_RE = /^(?:(?:http|ws)(s)?:\/\/)?(.*?)\/*(?:\/api\/)?$/;
function fixUrl(url) {
// Add HTTP protocol if missing.
if (!/^https?:/.test(url)) {
url = 'http:'+ url;
}
var matches = URL_RE.exec(url);
var isSecure = !!matches[1];
var rest = matches[2];
url = parseUrl(url);
// Suffix path with /api/ if missing.
var path = url.pathname || '';
if ('/' !== path[path.length - 1]) {
path += '/';
}
if (!/\/api\/$/.test(path)) {
path += 'api/';
}
// Reconstruct the URL.
return [
url.protocol, '//',
url.host,
path,
url.search,
url.hash,
isSecure ? 'wss' : 'ws',
'://',
rest,
'/api/',
].join('');
}

View File

@ -0,0 +1,38 @@
'use strict';
//====================================================================
var expect = require('must');
//====================================================================
describe('fixUrl()', function () {
var fixUrl = require('./').fixUrl;
describe('protocol', function () {
it('is added if missing', function () {
expect(fixUrl('localhost/api/')).to.equal('ws://localhost/api/');
});
it('HTTP(s) is converted to WS(s)', function () {
expect(fixUrl('http://localhost/api/')).to.equal('ws://localhost/api/');
expect(fixUrl('https://localhost/api/')).to.equal('wss://localhost/api/');
});
it('is not added if already present', function () {
expect(fixUrl('ws://localhost/api/')).to.equal('ws://localhost/api/');
expect(fixUrl('wss://localhost/api/')).to.equal('wss://localhost/api/');
});
});
describe('/api/ path', function () {
it('is added if missing', function () {
expect(fixUrl('ws://localhost')).to.equal('ws://localhost/api/');
expect(fixUrl('ws://localhost/')).to.equal('ws://localhost/api/');
});
it('is not added if already present', function () {
expect(fixUrl('ws://localhost/api/')).to.equal('ws://localhost/api/');
});
});
});

View File

@ -19,7 +19,7 @@
"node": ">=0.8.0"
},
"scripts": {
"test": "gulp test"
"test": "mocha index.spec.js"
},
"files": [
"index.js"
@ -29,5 +29,9 @@
"lodash.assign": "^2.4.1",
"lodash.foreach": "^2.4.1",
"ws": "^0.4.31"
},
"devDependencies": {
"mocha": "^2.1.0",
"must": "^0.12.0"
}
}