Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

allow request.defaults to override the main request method

  • Loading branch information...
commit 8cf019c9f9f719694408840823e92da08ab9dac3 1 parent db80bf0
@polotek polotek authored
Showing with 46 additions and 5 deletions.
  1. +13 −3 main.js
  2. +33 −2 tests/test-defaults.js
View
16 main.js
@@ -802,16 +802,23 @@ module.exports = request
request.initParams = initParams;
-request.defaults = function (options) {
+request.defaults = function (options, requester) {
var def = function (method) {
var d = 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]
}
- return method(params.options, params.callback)
+ if(typeof requester === 'function') {
+ if(method === request) {
+ method = requester;
+ } else {
+ params.options._requester = requester;
+ }
+ }
+ return method(params.options, params.callback);
}
- return d
+ return d;
}
var de = def(request)
de.get = def(request.get)
@@ -861,6 +868,9 @@ request.head = function (uri, options, callback) {
request.del = function (uri, options, callback) {
var params = initParams(uri, options, callback);
params.options.method = 'DELETE'
+ if(typeof params.options._requester === 'function') {
+ request = params.options._requester;
+ }
return request(params.uri || null, params.options, params.callback)
}
request.jar = function () {
View
35 tests/test-defaults.js
@@ -61,8 +61,39 @@ s.listen(s.port, function () {
request.defaults({headers:{foo:"bar"}}).head({uri: s.url + '/head'}, function (e, r, b){
if (e) throw e;
counter += 1;
- console.log(counter.toString() + " tests passed.")
- s.close()
});
+ s.on('/get_custom', function(req, resp) {
+ assert.equal(req.headers.foo, 'bar');
+ assert.equal(req.headers.x, 'y');
+ resp.writeHead(200, {'Content-Type': 'text/plain'});
+ resp.end();
+ });
+
+ // test custom request handler function
+ var defaultRequest = request.defaults({
+ headers:{foo:"bar"}
+ , body: 'TESTING!'
+ }, function(uri, options, callback) {
+ var params = request.initParams(uri, options, callback);
+ options = params.options;
+ options.headers.x = 'y';
+
+ return request(params.uri, params.options, params.callback);
+ });
+
+ var msg = 'defaults test failed. head request should throw earlier';
+ assert.throws(function() {
+ defaultRequest.head(s.url + '/get_custom', function(e, r, b) {
+ throw new Error(msg);
+ });
+ counter+=1;
+ }, msg);
+
+ defaultRequest.get(s.url + '/get_custom', function(e, r, b) {
+ if(e) throw e;
+ counter += 1;
+ console.log(counter.toString() + " tests passed.");
+ s.close();
+ });
})
Please sign in to comment.
Something went wrong with that request. Please try again.