I have create a UserService as follows:
angular.module('nrApp').factory('userService', ['Restangular', 'UserModel', 'DSCacheFactory', function (Restangular, UserModel, DSCacheFactory) {
// Create a new cache called "profileCache"
var userCache = DSCacheFactory('userCache', {
maxAge: 3600000,
deleteOnExpire: 'aggressive',
storageMode: 'localStorage', // This cache will sync itself with `localStorage`.
onExpire: function (key, value) {
Restangular.oneUrl('users', key).get().then(function(data) {
userCache.put(key, data);
});
}
});
Restangular.extendModel('users', function(obj) {
return UserModel.mixInto(obj);
});
Restangular.addRequestInterceptor(function(element, operation, what, url) {
if(operation === 'get') {
debugger;
//Check the cache to see if the resource is already cached
var data = userCache.get(url);
//If cache object does exist, return it
if(data !== undefined) {
angular.extend(element, data);
}
return element;
}
});
Restangular.addResponseInterceptor(function(data, operation, what, url, response) {
//Cache the response from a get method
if(operation === 'get') {
debugger;
userCache.put(url, data);
}
//Unvalidate the cache when a 'put', 'post' and 'delete' is performed to update the cached version.
if (operation === 'put' || operation === 'post' || operation === 'delete') {
userCache.destroy();
}
return response;
});
return Restangular.service('users');
}]);
From the comments it can be seen that what I am trying to achieve is whenever a Get request is performed through this service using Restangular the local cache is checked and if the cache returns an object it is extended into the restangular element. The flow that want to achieve is that of cancelling the request to the sever when a cache object is found for that request.
However without any luck the addResponseInterceptor method still executes even though the object was found in the cache.
Are there any possible solutions to cancelling the request to the sever during a 'Get' request?
Thanks! :)
One way to go about it would be to cancel it via httpConfig. Restangular gives you httpConfig object as a parameter in the addFullRequestInterceptor method. You could use that like in the following:
RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params, httpConfig ) {
...
if found in cache {
var defer = $q.defer();
httpConfig.timeOut = defer.promise;
defer.resolve();
}
...
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With