1

I am using $cacheFactory, I like it because it will increase performance by not calling service data all the times. But my doubt is on update of existing data, how can I update $cacheFactory data

service.query = function(queryCriteria) {
  var deferred = $q.defer();
  var req = {
    method: 'GET',
    url: BASE_URL + '/ticketCategories' + '?' + ApplicationUtil.parseQueryCriteria(queryCriteria),
    headers: {
      'Authorization': APP_CONSTANTS.STRATAGIES.BEARER + ' ' + ApplicationStorage.getJwtToken()
    },
    cache: true
  };
  var cache = $cacheFactory(Math.random());
  var data = cache.get("ticketCategories");
  if (!data) {
    $http(req).then(function(payload) {
      deferred.resolve(payload.data);
      cache.put("ticketCategories", payload.data);
    }, function(reason) {
      Logger.error(reason, 'Error querying ticket categories');
      deferred.reject(reason);
    });
  } else {
    return data;
  }
  return deferred.promise;
};

1 Answer 1

1

A sample implementation using your code could look like this.

var cache = $cacheFactory(Math.random());

service.query = function(queryCriteria) {
    var deferred = $q.defer();
    var req = {
        method: 'GET',
        url: BASE_URL + '/ticketCategories' + '?' + ApplicationUtil.parseQueryCriteria(queryCriteria),
        headers: {
            'Authorization': APP_CONSTANTS.STRATAGIES.BEARER + ' ' + ApplicationStorage.getJwtToken()
        },
        cache: true
    };
    var data = cache.get("ticketCategories");
    if (!data) {
        $http(req).then(function(payload) {
            deferred.resolve(payload.data);
            cache.put("ticketCategories", payload.data);
        }, function(reason) {
            Logger.error(reason, 'Error querying ticket categories');
            deferred.reject(reason);
        });
    } else {
        return data;
    }
    return deferred.promise;
};

service.refresh = function (queryCriteria) {
    // removes all cached entries
    cache.removeAll();
    // force reload, still returns the promise
    return service.query(queryCriteria);
};
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Daniel. If I put more data in cacheFactory like ticketCategories, tickets, faqs. Suggest in that case
You can also remove elements from cache by id. That would look like this: cache.remove('ticketCategories'); in your case. Read more here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.