restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Add local configuration for $http

Open julien-duponchelle opened this issue 13 years ago • 18 comments

Hi,

In order to have a better UX experience we want to be able to served a cached response before serving a real response.

Something like that: https://github.com/bennadel/DeferredWithUpdate.js

Do you think it's something that can be implemented inside restangular?

julien-duponchelle avatar Oct 07 '13 18:10 julien-duponchelle

Hey,

You can do that by setting values to $cache. You can set a $cache to $http (Restangular uses $http below). And then, you can set responses to a certain URL in the $cache. That way, you'll get the cached content :).

Does that make sense?

mgonto avatar Oct 07 '13 18:10 mgonto

Sorry, i'm not clear

With cached will serve a cached version. But i want:

  • serve a cached version of the data
  • trigger the HTTP query
  • when the http response is OK, refresh my data

For examples:

  • First session i got my twitter timeline from twitter server
  • The answer is locally cached
  • Second session i display the cached version
  • I trigger a GET on Twitter server
  • When the request finish i update my data

I can manually do it, but i'm asking about an elegant way to do it in Restangular.

julien-duponchelle avatar Oct 07 '13 19:10 julien-duponchelle

Hey,

There's no way of doing that with Restangular. All you can do, is just to cache requests that you don't want to be sent. That's it.

I like this feature, and I think this would be cool. If you want, you can create a Pull Request with the implementation and I'll merge it to Restangular.

Thanks!

mgonto avatar Oct 07 '13 19:10 mgonto

You can do that by setting values to $cache. You can set a $cache to $http (Restangular uses $http below). And then, you can set responses to a certain URL in the $cache.

With $http I can supply a different cache for every request. Is such fine-grained caching supported in restangular? As I understand, with RestangularProvider.setDefaultHttpFields({cache: true}); restangular will cache all and every request, what I do not want. Am I wrong?

ghost avatar Oct 10 '13 13:10 ghost

You're right. I need to implement that per request, so that you can send it.

Thanks for reminding me :)

mgonto avatar Oct 11 '13 01:10 mgonto

Setting this as an Enhancement to implement that

mgonto avatar Oct 11 '13 01:10 mgonto

Added support for this. Please let me know if this works for you

mgonto avatar Nov 09 '13 20:11 mgonto

What would be the best way to implement this? Building your own cache that returns another promise that finally resolves to real data?

rogerbraun avatar Nov 11 '13 14:11 rogerbraun

We implement it like that in our code:

getCacheList(Restangular.all('articles/recents'), {"per": page_size}, function (articles) {
      $scope.recentArticles = articles;
});

getCacheList store the articles inside local storage. The callback is called twice first time for the cached version and second time for the version from network. But i'm not happy with this api.

julien-duponchelle avatar Nov 11 '13 15:11 julien-duponchelle

@noplay That's really cool!

Would you care to share the code and maybe we could make it a Restangular plugin? What do you think?

mgonto avatar Nov 11 '13 15:11 mgonto

I just did something similar, namely this:

angular.module('someApp')
  .service('CacheFirst', function CacheFirst() {
    this.cachedData = {};
    var that = this;
    this.cache = function(key, promise) {

      // Update the cache after we finish
      promise.then(function (data) {
        that.cachedData[key] = data;
      });

      return function(cache, promise){

        promise.preliminary = function(callback) {
          if(cache[key] != undefined) {
            callback(cache[key]);
          }
          return promise;
        }

        promise.update = function(callback) {
          promise.preliminary(callback);
          return promise.then(callback);
        }
        return promise;
      }(this.cachedData, promise);
    }
  });

You can call it like this:

var promise = Restangular.all('comments').getList();
CacheFirst.cache('somekey', promise).update(function(){...})

You can also use different callbacks for the preliminary and final data. This wraps any kind of promise, so you can use it with Restangular or whatever else.

rogerbraun avatar Nov 11 '13 15:11 rogerbraun

That's really cool guys. I think it's an useful feature and I'd like to add it as a plugin.

If you guys want, we can chat and get one solution based on all of yours and make it a plugin to use :).

What do you guys think? @rogerbraun @noplay

mgonto avatar Nov 11 '13 16:11 mgonto

It would be wonderful to have this functionality in a plugin. I don't know if I am really satisfied with my solution, as @noplay said about his, but I'd love to help make this an available feature.

rogerbraun avatar Nov 11 '13 23:11 rogerbraun

Awesome, let's discuss an implementation about this :). Please, both send yours and we can make together a merged one

mgonto avatar Nov 11 '13 23:11 mgonto

My contribution to the discussion.

This is my implementation:

function getCache(type, restangularObj, options, cacheCallback) {
    var cache_key = restangularObj.getRestangularUrl() + JSON.stringify(options);

    if (type == "one") {
        var promise = restangularObj.get(options);
    }
    else {
        var promise = restangularObj.getList(options);
    }
    var deferred = $q.defer();
    promise.then(function(data) {
        localStorage.setItem(cache_key, JSON.stringify(data));
        cacheCallback(data);
        deferred.resolve(data);
    }, function(data) {
        deferred.reject(data);
    });

    var item = localStorage.getItem(cache_key);
    if (item) {
        cacheCallback(JSON.parse(item));
    }
    return deferred.promise;
}

function getCacheOne(restangularObj, options, cacheCallback) {
    return getCache("one", restangularObj, options, cacheCallback);
}

function getCacheList(restangularObj, options, cacheCallback) {
    return getCache("list", restangularObj, options, cacheCallback);
}

// Sample Usage
getCacheOne(Restangular.one('spacerocket'), {}, function (spacerocket) {
    $scope.spacerocket = spacerocket;
});

julien-duponchelle avatar Nov 20 '13 15:11 julien-duponchelle

Any update on a plugin? This is awesome stuff guys.

ghost avatar Feb 17 '14 03:02 ghost

@mgonto any update on this?

cyprusglobe avatar Jan 23 '15 17:01 cyprusglobe

It seems that the code for getCache from the last @noplay comment creates a Restangular request each time when getCache is hit. In order to prevent that I did the following:

        function getCache(type, restangularObj, options, cacheCallback) {

            var cache_key = restangularObj.getRestangularUrl() + JSON.stringify(options);
            var deferred = $q.defer();
            var item = localStorage.getItem(cache_key);

            if (item) {
                cacheCallback(JSON.parse(item));
                deferred.resolve(item);
            } else {

                if (type == "one") {
                    var promise = restangularObj.get(options);
                }
                else {
                    var promise = restangularObj.getList(options);
                }

                promise.then(function(data) {
                    localStorage.setItem(cache_key, JSON.stringify(data));
                    cacheCallback(data);
                    deferred.resolve(data);
                }, function(data) {
                    deferred.reject(data);
                });
            }

            return deferred.promise;
        }

valtumi avatar Dec 15 '15 01:12 valtumi