javascript - Generating a unique value for a header on each $http call -
i have large angularjs application , logging purposes, being tasked adding custom header of our http requests app contain a unique id each request. more valuable our api calls, of i'm aiming requests (getting templates, styles, etc.)
i using provider decorator patch each of methods exposed $httpprovider
(implementation based on this post), attempt call id method each time 1 of $http
methods runs, , add appropriate header:
module.config([ '$provide', function ($provide) { $provide.decorator('$http', [ '$delegate', function adduniqueidheader($http) { var httpmethods = ['get', 'post', 'put', 'patch', 'delete']; /** * patched http factory function adds request id each time called. * @param {string} method - valid http method. * @return {function} function sets various request properties. */ function httpwithheader(method) { return function(url, data, config) { config = config || {}; config.headers = config.headers || {}; // magic config.headers['my-custom-header'] = auniqueid(); data = data || {}; config.method = method.touppercase(); // return `$http` modified config, adding url , data passed in // `_.extend()` lodash, not underscore. return $http(_.extend(config, { url: url, data: data })); } }; // orginal methods , patch _.each(httpmethods, function (httpmethod) { var backupmethod = '_' + httpmethod; $http[backupmethod] = $http[httpmethod]; $http[httpmethod] = httpwithheader(httpmethod); }); return $http; } ]); } ]);
what have far works of time, doesn't seem work consistently (some api requests have it, don't). should note using quite old version of angularjs (1.0.6) , no, cannot upgrade (as love to) use of request interceptors not possible. additionally, use restangular majority of our api interactions.
my question is, using provider decorator right way go? if so, there cleaner way add header without having override/patch each individual http method i'm overlooking?
thanks in advance.
i ended solving issue utilizing restangular's request interceptors, since version of angular use doesn't have them baked in.
Comments
Post a Comment