Giter VIP home page Giter VIP logo

Comments (12)

mgonto avatar mgonto commented on July 16, 2024

Actually, ngResource uses $http "below", so you do get all the functionality from $http. If you want to cache something, you can just use the $cacheFactory set the URL and it'll be cached in $http, and therefore in $resource as well.

Same thing happens with default headers as you can see in the FAQ on how to add them.

from restangular.

mgonto avatar mgonto commented on July 16, 2024

Have you tried this?

from restangular.

roboncode avatar roboncode commented on July 16, 2024

An example would be helpful. Thanks Rob

from restangular.

mgonto avatar mgonto commented on July 16, 2024

Hey,

Take a look at this issue: #25

You'll have the example in the tests from AngularJS commit :).

Bests,
Gonto

from restangular.

roboncode avatar roboncode commented on July 16, 2024

Ok. Makes sense. Thanks for the reference.

from restangular.

mgonto avatar mgonto commented on July 16, 2024

No problem :). Glad to help!

from restangular.

mgonto avatar mgonto commented on July 16, 2024

As implementation on Angular's side wasn't really cool about caching (Tried out today), I've implemented it on Restangular.

In order to cache, you can do this:

https://github.com/mgonto/restangular#can-i-cache-requests

from restangular.

mikermcneil avatar mikermcneil commented on July 16, 2024

@mgonto @roboncode anyone else tried this with localstorage (/a localstorage wrapper around restangular in general?)

Thanks!

from restangular.

sdbondi avatar sdbondi commented on July 16, 2024

@mgonto I need more fine grained caching - for e.g how would I cache a getList call?

Something like:

myService = Restangular.service('people');
myService.getList('featured', {}, {cache: $resourceCache })

EDIT:

Doing this, which is not super succinct but works:

service = Restangular.all('people/featured')
service.withHttpConfig({cache: $resourceCache})
service.getList()

@mikermcneil BTW $resourceCache in my example is an instance of angular-cache which can use localStorage (http://angular-data.pseudobry.com/documentation/guide/angular-cache)

from restangular.

bostrom avatar bostrom commented on July 16, 2024

Continuing this old thread, is there any way to cache a single getList request issued on a Restangular service? Example:

myService = Restangular.service('people');

// single record is ok
myService.one(12).withHttpConfig({cache: true}).then();

// how to do it with get list?
myService.withHttpConfig({cache: true}) // no such method .withHttpConfig()
myService.all().withHttpConfig({cache: true}) // no such method .all()

The method above to use Restangular.all('people').withHttpConfig({cache: true}).getList() is a possible workaround in some cases, but not when the service originates from a locally configured Restangular.withConfig().service(). The configuration will be lost when issuing the query from the unconfigured Restangular object.

Maybe add .withHttpConfig or .all to the service?

from restangular.

isometriq avatar isometriq commented on July 16, 2024

If found a way that works.
I declare a singleton (service) for keeping a global cache object

angular
        .module('app.services')
        .service('APICache', APICache);

function APICache($cacheFactory, $window) {
    return $cacheFactory('http');
}

Then I use this singleton my Restangular derived factory

angular
    .module('app.services')
    .factory('API', API);

function API(Restangular, APICache) {

    var cache = APICache;
    var cacheTime = (new Date()).getTime();
    var cacheExpiration = 1000 * 60 * 5; // 5 min

    return Restangular.withConfig(function(RestangularConfigurer) {

        RestangularConfigurer
            .setDefaultHttpFields({cache:cache})

            .setResponseInterceptor(function(response, operation) {

                var currentTime = (new Date()).getTime();
                var cacheExpired = (currentTime - cacheTime) > cacheExpiration;

                if (cacheExpired || operation === 'put' || operation === 'post' || operation === 'delete') {
                    cache.removeAll();
                    cacheTime = (new Date()).getTime();
                }

                return response;
            })
    });
}

Then I can do all kind of request that will be cached and invalidated after 5min or when a modification request occurs.

When I want to clear the cache "permanently" (for the next requests), I have to inject APICache where I use it and call APICache.removeAll();.

Note that this is not perfect ..yet. We could remove only specific routes and the 5min delay is not reset. I think that APICache could be a wrapper instead of an extension of $cacheFactory('http') ..and could include all timing data, etc...

Another approach could be make API a singleton that includes a Restangular service instance and a $cacheFactory instance. Then put method to control the cache or to use the api... only ideas

from restangular.

isometriq avatar isometriq commented on July 16, 2024

Here my final version with a wrapper around the cache factory instance

(function() {

    'use strict';

    angular
        .module('app.services')
        .factory('API', API);

    function API(Restangular, APICache, $window) {

        var headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/x.api.v1+json'
        };

        return Restangular.withConfig(function(RestangularConfigurer) {

            RestangularConfigurer
                .setBaseUrl('/api')
                .setDefaultHeaders(headers)
                .setDefaultHttpFields({cache:APICache.getCache()})

                .setErrorInterceptor(function(response, operation) {

                     if (response.status === 422 || response.status === 401) {
                         if (response.data.errors) {
                             for (var error in response.data.errors) {
                                 //ngToast.danger({className: 'danger', content: response.data.errors[error][0]});
                                 return response.data.errors[error][0];
                             }
                         }
                         if (response.message) {
                             //ngToast.danger({className: 'danger', content: response.message});
                             return response.message;
                         }
                     }

                     if (response.status === 500) {
                         if (response.message) {
                             //ngToast.danger({className: 'danger', content: response.message});
                             return response.message;
                         }
                     }
                })

                .setResponseInterceptor(function(response, operation) {

                    if (APICache.isExpired() || operation === 'put' || operation === 'post' || operation === 'delete') {
                        APICache.reset();
                    }

                    return response;
                })

                .addFullRequestInterceptor(function (element, operation, what, url, headers) {

                    var token = $window.localStorage.satellizer_token;

                    if (token) {
                        headers.Authorization = 'Bearer ' + token;
                    }
                });
        });
    }

    angular
        .module('app.services')
        .service('APICache', APICache);

    function APICache($cacheFactory, $window) {

        var cache = $cacheFactory('http');
        var cacheTimer = (new Date()).getTime();
        var cacheExpiration = 1000 * 60 * 5; // 5 min

        this.getCache = function () {
            return cache;
        };

        this.isExpired = function() {
            var currentTime = (new Date()).getTime();
            var cacheExpired = (currentTime - cacheTimer) > cacheExpiration;
            return cacheExpired;
        };

        this.reset = function() {
            cacheTimer = (new Date()).getTime();
            cache.removeAll(); // todo could be improved/fine-tuned by passing type or url?
        };
    }

})();

from restangular.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.