From 11664fc0ac2ed168bb1ae989c57ae5a2074483a9 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Mon, 3 Mar 2014 13:44:50 +0100 Subject: [PATCH] Fixed automatic URL detection. Closes #8. --- params.js | 46 ++++++++++++++++++++++++++++++++++------------ test.js | 8 ++++++++ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/params.js b/params.js index 809700c..0197e6a 100644 --- a/params.js +++ b/params.js @@ -1,31 +1,47 @@ +var URL = require('url'); module.exports = function getParams(port, host, opts) { - var url = null; + var url = {}; + var parsed = null; + var result = ''; if ('object' === typeof port) { opts = port; - url = 'localhost'; + host = null; + port = null; } else if ('string' === typeof port) { - url = port; + host = port; + port = null; + opts = host; } if ('object' === typeof host) { opts = host; - } else if ('object' !== typeof opts) { - opts = {}; + host = null; } - if (!host) { - host = 'localhost' + if (!host && !port && process.title === 'browser') { + host = document.URL; } - if (!url && host && port) { - url = host + ':' + port; + url.host = host || 'localhost'; + url.port = port; + url.protocol = 'ws://'; + + try{ + parsed = URL.parse(host); + if (parsed.host) { + url.host = parsed.hostname; + url.port = parsed.port || port; + url.protocol = (parsed.protocol === 'https:') ? 'wss://' : 'ws://'; + url.protocol = (parsed.protocol === 'wss:') ? 'wss://' : 'ws://'; + } + } catch(e) { } - if (url.slice(0,5).toLowerCase() != "ws://" && url.slice(0,6).toLowerCase() != "wss://") { - url = "ws://" + url; + if ('object' !== typeof opts) { + opts = {}; } var websocketOpts = { @@ -36,8 +52,14 @@ module.exports = function getParams(port, host, opts) { websocketOpts.protocol = opts.protocol; } + result = url.protocol + url.host + + if (url.port) { + result += ':' + url.port + } + return { - url: url, + url: result, opts: opts, websocketOpts: websocketOpts } diff --git a/test.js b/test.js index 02675d1..bee2034 100644 --- a/test.js +++ b/test.js @@ -64,6 +64,14 @@ describe('MqttClient', function() { }); }); + if (process.title === 'browser') { + describe("specifying nothing", function() { + clientTests(function() { + return mqttOverWs.createClient(); + }); + }); + } + if (process.title === 'node') { describe("specifying a port, secure URL and secure client options", function(){ clientTests(function(){