Skip to content

Commit

Permalink
defaults(): use extend for "deep" defaulting
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
tcort committed May 9, 2016
1 parent 9e29831 commit b514a81
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* MIT Licensed
*
*/
var extend = require('extend');
var when = require('when');
var request = require('request');
var _ = require('fg-lodash');
Expand Down Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"license": "MIT",
"dependencies": {
"extend": "^3.0.0",
"fg-lodash": "0.0.2",
"request": "^2.62.x",
"when": "~3.7.5"
Expand Down
13 changes: 13 additions & 0 deletions test/defaults.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});

});

0 comments on commit b514a81

Please sign in to comment.