Indent is to cache API calls by intercepting request and response using AngularJS interceptor. Below is my current code. I don't know what to do if the request exist in the cache. Is this feasible? Is this the right way to do it?
app.factory('apiCacheMiddleware', apiCacheMiddleware);
function apiCacheMiddleware($cacheFactory) {
var cache = $cacheFactory('apiCache');
var interceptor = {
request: function(config) {
console.log(config)
if(config.method === 'GET' && cache.get(config.url)){
// What to return from here???
}
return config;
},
response: function(response) {
console.log(response);
if(response.config.method === 'GET'){
cache.put(response.config.url, response.data);
}
return response;
}
};
return interceptor;
};
What you need to do (if you still happen to need it) is to assign the cache you created with $cacheFactory to the request (config.cache = cache; – it will probably be useful to check the previous value and take some decision upon it). On the response then, you will fill in that cache as you already do, and AngularJS will take care of the rest.
Related
I have been looking at an application I made a while back and there is a particular page where the details are being loaded last. Because of this, it seems to be queuing the request (there are more than 6 others before it) and that is causing the page to be slow.
I figured I could find a solution to prioritize these requests and I found this:
How to prioritize requests in angular $http service?
So I created my version of it and added it to my interceptors:
// Add our auth interceptor to handle authenticated requests
$httpProvider.interceptors.push('authInterceptor');
$httpProvider.interceptors.push('httpPriorityInterceptor');
The interceptor looks like this:
function factory($injector, $q) {
var requestStack = [], // request stack
$http = null; // http service to be lazy loaded
return {
request: request,
responseError: responseError
};
//////////////////////////////////////////////////
function request(config) {
// Lazy load $http service
if (!$http) {
$http = $injector.get('$http');
}
if (!config.hasBeenRequested) {
config.hasBeenRequested = true;
config.priority = config.priority || 3;
console.log(config);
// add a copy of the configuration
// to prevent it from copying the timeout property
requestStack.push(angular.copy(config));
// sort each configuration by priority
requestStack = requestStack.sort(sort);
// cancel request by adding a resolved promise
config.timeout = $q.when();
}
// return config
return config;
}
function responseError(rejection) {
// check if there are requests to be processed
if (requestStack.length > 0) {
requestStack.reduceRight(function(promise, config) {
return promise.finally(function() {
return $http(config);
});
}, $q.when());
requestStack.length = 0;
}
// return rejected request
return $q.reject(rejection);
}
//////////////////////////////////////////////////
function sort(config1, config2) {
return config1.priority < config2.priority;
}
}
The problem is, it seems to be intercepting template requests too. I have no issue with that, but they are not resolving. Instead I get a lot of errors:
Error: [$templateRequest:tpload] Failed to load template: app/accounts/accounts.html (HTTP status: -1 )
Has anyone encountered this before? Is there something I can do to fix this?
you should know that every request such as html files , css file and ... comes into interceptor.
in your case you dont need to prioritize this files. so you can filter your request like:
if (config.url.toString().toLowerCase().includes("api")) {
//place your functionality
}
I want to cache the response [i.e. parsed JSON response] of HTTP requests rather than the response itself. My data is big and gzipped so there is actually a fair performance hit decompressing this so would like to store the raw data itself.
Currently I am using a HTTP Interceptor for caching and TimeToLive mechanics described here alongside AngularJS' built in $cacheFactory.
So how can I, using an intercepter, stop the HTTP request and return my own response. Note I still plan on using $cacheFactory, I'd just manage my own data.
.factory('cacheInterceptor', ['$cacheFactory', function($cacheFactory) {
return {
request: function(config) {
if (config.cache) {
// if we have stored this request, return it, else let the request happen naturally and cache after
// Things I don't know:
// How to return existing cache data and prevent the reqeust from happening
// Cache the data I get back from a HTTP request
}
return config;
}
};
}])
I would preffer to inject this into your service and make your factory only handle the data recived/cached. This time I only created a service for you which holds the logic of HTTP / Cache switch. I think you will be able to create a factory to handle your data/states on your own.
.service('getService', ['$cacheFactory', '$http', '$q', function($cacheFactory, $http, $q) {
return {
request: function() {
function getData () {
var deferred = $q.defer();
if (angular.isUndefined($cacheFactory.get('getServiceData'))) {
$http({
'method': 'GET',
'url': 'someUrl'
}).then(function (result) {
$cacheFactory.put('getServiceData', result.data);
deferred.resolve(result.data);
});
} else {
deferred.resolve($cacheFactory.get('getServiceData'));
}
}
return getData();
},
flush: function () {
$cacheFactory.remove('getServiceData');
},
refresh: function () {
this.flush();
return this.refresh();
}
};
}]);
it's enough to add {cache: true} to the request options.
see the here
$http.get('some/url', {cache: true})
.then( ({data}) => data)
I want to use request interceptor in my app to add verify code into requests (for CSRF protection). My code looks like this now:
$httpProvider.interceptors.push(function($q, $injector, AppConst) {
return {
request: function(request) {
var VerifyCodeService = $injector.get('VerifyCodeService');
var verifyCodeUrl = AppConst.apiUrl + '/app/verifyCode'
if(request.url!=verifyCodeUrl && request.data!=undefined){
VerifyCodeService.getCode()
.then(function(data) {
if (AppConst.serviceResponseOk==data.result) {
request.data.verifyCode = data.verifyCode;
return request;
} else {
console.log('error');
return request;
}
}, function(error) {
console.log('error:' + error);
return request;
});
} else {
return request;
}
}
};
});
But for some reason I keep getting this error:
TypeError: Cannot read property 'headers' of undefined
at serverRequest (angular.js:10028)
at processQueue (angular.js:14567)
at angular.js:14583
at Scope.$eval (angular.js:15846)
at Scope.$digest (angular.js:15657)
at Scope.$apply (angular.js:15951)
at done (angular.js:10364)
at completeRequest (angular.js:10536)
at XMLHttpRequest.requestLoaded (angular.js:10477)
Anyone knows whats happening?
If I read this right, you are making a XHR which triggers another XHR to get the CSRF token and add it to the original request's data object. I think the issue is the second XHR. This second request is async just like the first, so you can't just return from the then method.
Try returning the promise generated by your second XHR in your if statement (which is resolved in the inner then invocation after the second XHR by return request;).
if(request.url!=verifyCodeUrl && request.data!=undefined){
var secondXhr = VerifyCodeService.getCode()
.then(function(data) {
if (AppConst.serviceResponseOk==data.result) {
request.data.verifyCode = data.verifyCode;
return request;
} else {
console.log('error');
return request;
}
}, function(error) {
console.log('error:' + error);
return request;
});
return secondXhr;
} else {
return request;
}
From the Interceptors section of the Angular docs (bolding added):
request: interceptors get called with a http config object. The
function is free to modify the config object or create a new one. The
function needs to return the config object directly, or a promise
containing the config or a new config object.
On a different note, it looks like you are introducing a significant delay into each XHR since you are essentially blocking each request until the token is returned.
A different implementation where each response returns the new token for the next request in a header could work (as long as you don't have concurrent requests(!)), or CSRF token per page load (if you have full page reloads) might be options. I'm sure there are suggestions on the internets if you want to make that change.
I need to add some data to each response I send via $http in angular that will be in the response. In other works I'm trying to add an 'id' to the request because when the response is returned I need to associate it with the correct object that sent it. Is this possible? If so how would I go about it?
use interceptors, I'm quoting from the documentation:
For purposes of global error handling, authentication, or any kind of
synchronous or asynchronous pre-processing of request or
postprocessing of responses, it is desirable to be able to intercept
requests before they are handed to the server and responses before
they are handed over to the application code that initiated these
requests.
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
config.id = generateId(); //or a timestamp maybe?
return config;
},
'response': function(response) {
// do something on success
return response;
}
};
});
then add your
$httpProvider.interceptors.push('myHttpInterceptor');
I'm trying to figure out if it is possible to use a $http interceptor to cancel a request before it even happens.
There is a button that triggers a request but if the user double-clicks it I do not want the same request to get triggered twice.
Now, I realize that there's several ways to solve this, and we do already have a working solution where we wrap $http in a service that keeps track of requests that are currently pending and simply ignores new requests with the same method, url and data.
Basically this is the behaviour I am trying to do with an interceptor:
factory('httpService', ['$http', function($http) {
var pendingCalls = {};
var createKey = function(url, data, method) {
return method + url + JSON.stringify(data);
};
var send = function(url, data, method) {
var key = createKey(url, data, method);
if (pendingCalls[key]) {
return pendingCalls[key];
}
var promise = $http({
method: method,
url: url,
data: data
});
pendingCalls[key] = promise;
promise.finally(function() {
delete pendingCalls[key];
});
return promise;
};
return {
post: function(url, data) {
return send(url, data, 'POST');
}
}
}])
When I look at the API for $http interceptors it does not seem to be a way to achieve this. I have access to the config object but that's about it.
Am I attempting to step outside the boundaries of what interceptors can be used for here or is there a way to do it?
according to $http documentation, you can return your own config from request interceptor.
try something like this:
config(function($httpProvider) {
var cache = {};
$httpProvider.interceptors.push(function() {
return {
response : function(config) {
var key = createKey(config);
var cached = cache[key];
return cached ? cached : cached[key];
}
}
});
}
Very old question, but I'll give a shot to handle this situation.
If I understood correctly, you are trying to:
1 - Start a request and register something to refer back to it;
2 - If another request takes place, to the same endpoint, you want to retrieve that first reference and drop the request in it.
This might be handled by a request timeout in the $http config object. On the interceptor, you can verify it there's one registered on the current request, if not, you can setup one, keep a reference to it and handle if afterwards:
function DropoutInterceptor($injector) {
var $q = $q || $injector.get('$q');
var dropouts = {};
return {
'request': function(config) {
// I'm using the request's URL here to make
// this reference, but this can be bad for
// some situations.
if (dropouts.hasOwnProperty(config.url)) {
// Drop the request
dropouts[config.url].resolve();
}
dropouts[config.url] = $q.defer();
// If the request already have one timeout
// defined, keep it, othwerwise, set up ours.
config.timeout = config.timeout || dropouts[config.url];
return config;
},
'requestError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
},
'response': function(response) {
delete dropouts[response.config.url];
return response;
},
'responseError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
}
};
}