From 4b4d05979118b028f6d198ee1782c1b48a0ea8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Ma=C5=82ecki?= Date: Tue, 1 Nov 2011 16:23:30 +0100 Subject: [PATCH] tls: make `tls.connect` accept port and host in `options` Previous API used form: tls.connect(443, "google.com", options, ...) now it's replaced with: tls.connect({port: 443, host: "google.com", ...}, ...) It simplifies argument parsing in `tls.connect` and makes the API consistent with other parts. Fixes #1983. --- lib/tls.js | 47 +++++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/lib/tls.js b/lib/tls.js index 5a3afd9d38..dfac08484e 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -999,7 +999,7 @@ Server.prototype.SNICallback = function(servername) { // Target API: // -// var s = tls.connect(8000, "google.com", options, function() { +// var s = tls.connect({port: 8000, host: "google.com"}, function() { // if (!s.authorized) { // s.destroy(); // return; @@ -1011,24 +1011,31 @@ Server.prototype.SNICallback = function(servername) { // }); // // -// TODO: make port, host part of options! -exports.connect = function(port /* host, options, cb */) { - // parse args - var host, options = {}, cb; - for (var i = 1; i < arguments.length; i++) { - switch (typeof arguments[i]) { - case 'string': - host = arguments[i]; - break; - - case 'object': - options = arguments[i]; - break; - - case 'function': - cb = arguments[i]; - break; +exports.connect = function(/* [port, host], options, cb */) { + var options = {}, cb; + + if (typeof arguments[0] === 'object') { + options = arguments[0]; + } else if (typeof arguments[1] === 'object') { + options = arguments[1]; + options.port = arguments[0]; + } else if (typeof arguments[2] === 'object') { + options = arguments[2]; + options.port = arguments[0]; + options.host = arguments[1]; + } else { + // This is what happens when user passes no `options` argument, we can't + // throw `TypeError` here because it would be incompatible with old API + if (typeof arguments[0] === 'number') { + options.port = arguments[0]; } + if (typeof arguments[1] === 'string') { + options.host = arguments[1]; + } + } + + if (typeof arguments[arguments.length - 1] === 'function') { + cb = arguments[arguments.length - 1]; } var socket = new net.Stream(); @@ -1040,7 +1047,7 @@ exports.connect = function(port /* host, options, cb */) { options.rejectUnauthorized === true ? true : false, { NPNProtocols: this.NPNProtocols, - servername: options.servername || host + servername: options.servername || options.host }); if (options.session) { @@ -1052,7 +1059,7 @@ exports.connect = function(port /* host, options, cb */) { cleartext.on('secureConnect', cb); } - socket.connect(port, host); + socket.connect(options.port, options.host); pair.on('secure', function() { var verifyError = pair.ssl.verifyError();