I've been assigned the task of adding a unique ID for each request to all HTTP requests made by our AngularJS application for logging purposes. While this is more crucial for API calls, I'm currently working on implementing it for all kinds of requests including templates and styles.
My approach involves using a provider decorator to modify the methods provided by $HttpProvider
. This method, inspired by this post, aims to inject the ID into the header of every $http
call:
module.config([
'$provide',
function ($provide) {
$provide.decorator('$http', [
'$delegate',
function addUniqueIdHeader($http) {
var httpMethods = ['get', 'post', 'put', 'patch', 'delete'];
/**
* Modifies HTTP factory function to include a request ID with each call.
* @param {string} method - An HTTP method.
* @return {function} A modified function setting various request properties.
*/
function httpWithHeader(method) {
return function(url, data, config) {
config = config || {};
config.headers = config.headers || {};
// adding custom header
config.headers['My-Custom-Header'] = generateUniqueId();
data = data || {};
config.method = method.toUpperCase();
// returns $http with updated configuration
return $http(_.extend(config, {
url: url,
data: data
}));
}
};
// backup original methods and patch them
_.each(httpMethods, function (httpMethod) {
var backupMethod = '_' + httpMethod;
$http[backupMethod] = $http[httpMethod];
$http[httpMethod] = httpWithHeader(httpMethod);
});
return $http;
}
]);
}
]);
The current implementation works intermittently; some API requests have the ID while others don't. It's important to note that we are constrained to an older version of AngularJS (1.0.6) and cannot upgrade at the moment, ruling out the possibility of using request interceptors. Additionally, Restangular is widely used in our API interactions.
My question is whether utilizing a provider decorator is the correct approach here. If so, is there a more efficient way to incorporate the unique header without having to override or patch each individual HTTP method?
Appreciate any insights in advance.