From 7e6a7f3b07371be1fa03982789a1290df3832857 Mon Sep 17 00:00:00 2001 From: Josh Gruenberg Date: Thu, 21 Jan 2016 18:24:10 -0500 Subject: [PATCH] Prevent options object from being mutated. Fixes #230. --- lib/restler.js | 8 ++++---- test/restler.js | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/lib/restler.js b/lib/restler.js index 74bd41f..86d207b 100644 --- a/lib/restler.js +++ b/lib/restler.js @@ -310,8 +310,8 @@ mixin(Request.prototype, { } }); -function shortcutOptions(options, method) { - options = options || {}; +function shortcutOptions(opts, method) { + var options = mixin({}, opts); options.method = method; options.parser = (typeof options.parser !== "undefined") ? options.parser : parsers.auto; parsers.xml.options = (typeof options.xml2js == 'undefined') ? {} : options.xml2js; @@ -349,8 +349,8 @@ function head(url, options) { return request(url, shortcutOptions(options, 'HEAD')); } -function json(url, data, options, method) { - options = options || {}; +function json(url, data, opts, method) { + var options = mixin({}, opts); options.parser = (typeof options.parser !== "undefined") ? options.parser : parsers.auto; options.headers = options.headers || {}; options.headers['content-type'] = 'application/json'; diff --git a/test/restler.js b/test/restler.js index 819a6e2..86b7cf1 100644 --- a/test/restler.js +++ b/test/restler.js @@ -641,6 +641,24 @@ module.exports['Deserialization'] = { }).on('fail', function() { test.ok(false, 'should not have got here'); }); + }, + + 'Should parse JSON without mutating options': function(test) { + var options = {}; + rest.get(host + '/json', options).on('complete', function(data) { + test.equal(data.ok, true, 'returned: ' + util.inspect(data)); + test.deepEqual({}, options, 'mutated: ' + util.inspect(options)); + test.done(); + }); + }, + + 'Should post and parse JSON without mutating options': function(test) { + var obj = { secret : 'very secret string' }, options = {}; + rest.json(host + '/push-json', obj, options, 'POST').on('complete', function(data) { + test.equal(obj.secret, data.secret, 'returned: ' + util.inspect(data)); + test.deepEqual({}, options, 'mutated: ' + util.inspect(options)); + test.done(); + }); } };