From d88e863019fc5239f2a5e01ba3fd05de1923a8c3 Mon Sep 17 00:00:00 2001 From: Pawel Kozlowski Date: Fri, 2 Jan 2015 18:27:21 +0100 Subject: [PATCH] feat($http): provide a config object as an argument to header functions --- src/ng/http.js | 8 ++++---- test/ng/httpSpec.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/ng/http.js b/src/ng/http.js index b65e6639f3e1..e79284163443 100644 --- a/src/ng/http.js +++ b/src/ng/http.js @@ -615,7 +615,7 @@ function $HttpProvider() { * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the - * header will not be sent. + * header will not be sent. Functions accept a config object as an argument. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – @@ -834,12 +834,12 @@ function $HttpProvider() { : $q.reject(resp); } - function executeHeaderFns(headers) { + function executeHeaderFns(headers, config) { var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { - headerContent = headerFn(); + headerContent = headerFn(config); if (headerContent != null) { processedHeaders[header] = headerContent; } @@ -873,7 +873,7 @@ function $HttpProvider() { } // execute if header value is a function for merged headers - return executeHeaderFns(reqHeaders); + return executeHeaderFns(reqHeaders, shallowCopy(config)); } } diff --git a/test/ng/httpSpec.js b/test/ng/httpSpec.js index 864b3b846027..e3096edbb1b4 100644 --- a/test/ng/httpSpec.js +++ b/test/ng/httpSpec.js @@ -781,6 +781,34 @@ describe('$http', function() { $httpBackend.flush(); }); + it('should expose a config object to header functions', function() { + var config = { + foo: 'Rewritten', + headers: {'Accept': function(config) { + return config.foo; + }} + }; + + $httpBackend.expect('GET', '/url', undefined, {Accept: 'Rewritten'}).respond(''); + $http.get('/url', config); + $httpBackend.flush(); + }); + + it('should not allow modifications to a config object in header functions', function() { + var config = { + headers: {'Accept': function(config) { + config.foo = 'bar'; + return 'Rewritten'; + }} + }; + + $httpBackend.expect('GET', '/url', undefined, {Accept: 'Rewritten'}).respond(''); + $http.get('/url', config); + $httpBackend.flush(); + + expect(config.foo).toBeUndefined(); + }); + it('should check the cache before checking the XSRF cookie', inject(function($browser, $cacheFactory) { var testCache = $cacheFactory('testCache'), executionOrder = [];