Search code examples
angularjsangular-http-interceptors

Angular js interceptor that returns a cached response


I want to make a angularJS interceptor that when the client is offline returns instead of an error a cached response as if it wasn't any error.

What I've done so far was to make an interceptor that caches the api requests:

app.factory('httpCachingInterceptor', function ($q, apiCache) {
return {

  'response' : function(response) {
    // cache the api
    if (response.config.url.indexOf('api/') > 0)
      apiCache.addApiCache(response.config.url, response.data);
    return response;
  },

  'responseError' : function(rejection) {
    if (rejection.status == -1) {
      // get the data from apiCache
      // 
      apiCache.getApiCache(rejection.config.url, function(data) {
        // build a new promise and return it as a valid response

      })
    }
    return $q.reject(rejection);
  }

 }
})

I've noticed that when offline the rejection.status is -1 so that's when I check if a request was made while offline.

My question is how I build the response? Should I make a new promise or can I update the rejection?


Solution

  • I managed to make it work like this:

    'responseError' : function(rejection) {
        if (rejection.status == -1) {
          // get the data from apiCache
          var deferred = $q.defer();
    
          apiCache.getApiCache(rejection.config.url, function(err, data) {
            if (err || !data) {
              return deferred.reject(rejection);
            }
            rejection.data = data;
            rejection.status = 200;
            deferred.resolve(rejection);
            console.log("Resolve promise with ", rejection);
          })
    
          return deferred.promise;
        }
        return $q.reject(rejection);
     }
    

    So i made a new promise and modified the rejection I got with the new data from the cache.