diff --git a/lib/restler.js b/lib/restler.js index bf6cc57..6807268 100644 --- a/lib/restler.js +++ b/lib/restler.js @@ -63,12 +63,15 @@ function Request(uri, options) { console.log("Building multipart request without Content-Length header, please specify all file sizes"); } } else { - if (typeof this.options.data == 'object') { + if (this.options.data instanceof Buffer) { + this.options.data = new Buffer(this.options.data.toString(), this.options.encoding || 'utf8'); + } + else if (typeof this.options.data == 'object') { this.options.data = qs.stringify(this.options.data); this.headers['Content-Type'] = 'application/x-www-form-urlencoded'; this.headers['Content-Length'] = this.options.data.length; } - if(typeof this.options.data == 'string') { + else if(typeof this.options.data == 'string') { var buffer = new Buffer(this.options.data, this.options.encoding || 'utf8'); this.options.data = buffer; this.headers['Content-Length'] = buffer.length; @@ -229,7 +232,6 @@ mixin(Request.prototype, { }, run: function() { var self = this; - if (this.options.multipart) { multipart.write(this.request, this.options.data, function() { self.request.end(); @@ -368,12 +370,14 @@ var parsers = { }, json: function(data, callback) { if (data && data.length) { + var json = null, + err = null; try { - callback(null, JSON.parse(data)); - } catch (err) { + json = JSON.parse(data); + } catch (err) { err.message = 'Failed to parse JSON body: ' + err.message; - callback(err, null); } + callback(err, json); } else { callback(null, null); } @@ -470,6 +474,16 @@ mixin(Service.prototype, { }, _withDefaults: function(options) { var o = mixin({}, this.defaults); + if( options ) { + if(o.headers && options.headers) { + mixin(o.headers, options.headers); + delete options.headers; + } + if(o.query && options.query) { + mixin(o.query, options.query); + delete options.query; + } + } return mixin(o, options); } });