Skip to content

Commit

Permalink
defaults: merge headers
Browse files Browse the repository at this point in the history
  • Loading branch information
aj0strow committed Jun 26, 2014
1 parent 83dfba3 commit 6a0add7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
15 changes: 11 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,18 @@ request.initParams = initParams

request.defaults = function (options, requester) {
var def = function (method) {
var d = function (uri, opts, callback) {
return function (uri, opts, callback) {
var params = initParams(uri, opts, callback)
for (var i in options) {
if (params.options[i] === undefined) params.options[i] = options[i]
Object.keys(options).forEach(function (key) {
if (key !== 'headers' && params.options[key] === undefined) {
params.options[key] = options[key]
}
})
if (options.headers) {
var headers = {}
util._extend(headers, options.headers)
util._extend(headers, params.options.headers)
params.options.headers = headers
}
if(typeof requester === 'function') {
if(method === request) {
Expand All @@ -79,7 +87,6 @@ request.defaults = function (options, requester) {
}
return method(params.options, params.callback)
}
return d
}
var de = def(request)
de.get = def(request.get)
Expand Down
17 changes: 17 additions & 0 deletions tests/test-defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,23 @@ s.listen(s.port, function () {
counter += 1;
});

s.on('/merge-headers', function (req, resp) {
assert.equal(req.headers.foo, 'bar')
assert.equal(req.headers.merged, 'yes')
resp.writeHead(200)
resp.end()
});

request.defaults({
headers:{foo:"bar", merged:"no"}
})(s.url + '/merge-headers', {
headers:{merged:"yes"}
}, function (e, r, b){
if (e) throw e
assert.equal(r.statusCode, 200)
counter += 1
});

s.on('/post', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.headers['content-type'], null);
Expand Down

0 comments on commit 6a0add7

Please sign in to comment.