My goal is to accurately measure the time spent on HTTP requests in my application. I believe this should be done universally, so I want to implement an interceptor.
I have created an interceptor that can record the start and end times of each request:
app.factory('httpTimeInterceptor', [function() {
var start;
return {
request: function(config) {
start = new Date();
console.log("START",start);
return config;
},
response: function(response) {
console.log("START",start);
var date = new Date();
console.log("END",date);
return response;
}
};
}])
This setup logs three values to the console: the start time of the request, then again the start time and end time when the request concludes.
However, the issue arises when multiple requests are made simultaneously (the second starts before the first ends). This results in the start
variable being overwritten with a new value.
The problem lies in the fact that my interceptor is a factory, making it a singleton (please correct me if I'm mistaken).
Is there a way for me to modify my code to easily retrieve the actual time taken for each request?
I am considering creating an array to store keys for each request, allowing me to access the start time when the request finishes, but I'm unsure how to identify the same request in the request
and response
functions.
Perhaps there is a simpler solution to achieve what I am aiming for?