From 2ded40a5745733e548eaa81a76865564a0cf49ef Mon Sep 17 00:00:00 2001 From: Malte-Thorben Bruns Date: Tue, 21 Apr 2015 17:40:23 +0200 Subject: [PATCH] call: allow passing of url --- lib/call.js | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/lib/call.js b/lib/call.js index 07651be..d8e2df3 100644 --- a/lib/call.js +++ b/lib/call.js @@ -1,6 +1,7 @@ 'use strict'; var util = require('util'); var stream = require('stream'); +var parseURL = require('url').parse; var protocols = { http: require('http'), @@ -21,7 +22,7 @@ var ports = { * An API Call * * @param {RAIL} rail - * @param {?Object=} opt_options + * @param {?(Object|string)=} opt_options * * @constructor * @extends {stream.Writable} @@ -45,7 +46,7 @@ function Call(rail, opt_options) { this._interceptors = {}; // first plugin event - this.rail.emit('plugin-call', this, opt_options); + rail.emit('plugin-call', this, opt_options); // configure the first request this.__configure(opt_options); @@ -54,14 +55,42 @@ util.inherits(Call, stream.Writable); module.exports = Call; +Call.prototype._urlToOptions = function(options, url) { + var parsed = parseURL(url); + + options.proto = parsed.protocol.substr(0, parsed.protocol.length - 1); + + if (options.request) { + options.request.host = parsed.hostname; + options.request.port = parsed.port; + options.request.path = parsed.path; + } else { + options.host = parsed.hostname; + options.port = parsed.port ? parseInt(parsed.port, 10) : null; + options.path = parsed.path; + } + + return options; +}; + + /** + * @param {Object|string} options + * * @return {Object} */ Call.prototype.__configure = function(options) { - var i, keys; - var req = options.request; + var i, keys, req; var defaults = this.rail.defaults; + if (typeof options === 'string') { + options = this._urlToOptions({}, options); + } else if (typeof options.url === 'string') { + options = this._urlToOptions(options, options.url); + } + + req = options.request; + if (!req) { req = options; }