From b514a8161ece2d053ded9c52a6ba0a2fad65d6a2 Mon Sep 17 00:00:00 2001 From: Thomas Cort Date: Mon, 9 May 2016 10:10:01 -0400 Subject: [PATCH] defaults(): use extend for "deep" defaulting defaults() does shallow defaulting. For example, when the default options are `{ qs: { foo: 123 } }` and the options are `{ qs: { bar: 321 } }`, the resulting options are `{ qs: { bar: 321 } }`. It should instead do a "deep" merge of the options and default options. The result of the deep merge would be `{ qs: { foo: 123, bar: 321 } }`. Fix this issue by using [extend](https://github.com/justmoon/node-extend). This is what request [does](https://github.com/request/request/blob/master/index.js#L90). --- index.js | 5 +++-- package.json | 1 + test/defaults.test.js | 13 +++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index c237594..c01d175 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,7 @@ * MIT Licensed * */ +var extend = require('extend'); var when = require('when'); var request = require('request'); var _ = require('fg-lodash'); @@ -143,10 +144,10 @@ function defaults(defaultOptions, defaultF) { if (typeof options === "string") { options = { url: options }; } - return Factory.apply(null, [ _.defaults({}, options, defaultOptions), f || defaultF ]); + return Factory.apply(null, [ extend(true, {}, defaultOptions, options), f || defaultF ]); }; factory.defaults = function (newDefaultOptions, newDefaultF) { - return defaults.apply(null, [ _.defaults({}, newDefaultOptions, defaultOptions), newDefaultF || defaultF ]); + return defaults.apply(null, [ extend(true, {}, defaultOptions, newDefaultOptions), newDefaultF || defaultF ]); }; factory.Request = Request; factory.RetryStrategies = RetryStrategies; diff --git a/package.json b/package.json index 394d877..ac2d555 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ }, "license": "MIT", "dependencies": { + "extend": "^3.0.0", "fg-lodash": "0.0.2", "request": "^2.62.x", "when": "~3.7.5" diff --git a/test/defaults.test.js b/test/defaults.test.js index 0c29ccb..98cf698 100644 --- a/test/defaults.test.js +++ b/test/defaults.test.js @@ -53,4 +53,17 @@ describe('Defaults', function () { }); }); + it('should perform "deep" defaulting', function (done) { + var r = request.defaults({ + json: true, + qs: { d: "{index}" } + }); + r({ url: 'http://www.filltext.com/?rows=1', qs: { x: "test" } }, function (err, response, body) { + t.strictEqual(response.statusCode, 200); + t.strictEqual(body[0].d, 1); + t.strictEqual(body[0].x, "test"); + done(); + }); + }); + });