all files / angular-http-backup/src/ httpbackup.interceptor.js

100% Statements 16/16
100% Branches 2/2
100% Functions 3/3
100% Lines 16/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                                             
/**
 * Saves previously successful ajax requests in localStorage and replays them back when there’s server response fails/network error
 */
 
export default HttpBackupInterceptor;
 
/* @ngInject */
function HttpBackupInterceptor( $q, $log ) {
 
  return {
    response     : response,
    responseError: responseError
  };
 
  function response( response ) {
    // for every successful request, cache the response
    window.localStorage.setItem( response.config.url, JSON.stringify( response ) );
    return response;
  }
 
  function responseError( response ) {
    var data = window.localStorage.getItem( response.config.url );
    if ( data ) { //if response fails and there's cached data
 
      try {
        // use cached data
        data = JSON.parse( data );
        console.debug( 'using offline cache:', response.config.url );
        return $q.resolve( data );
      } catch ( ex ) {
        return $q.reject( response );
      }
    } else {
      return $q.reject( response );
    }
  }
}