Last active
October 21, 2019 20:34
-
-
Save aclave1/17f108eb9448ce0fd299 to your computer and use it in GitHub Desktop.
Angularjs auto retry after request failure and resolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = angular.module('app', []); | |
app | |
.factory('AuthToken', [ | |
'$http', | |
'$q', | |
'$window', | |
function($http, $q, $window) { | |
var authToken = {}; | |
//gets the token and sets it on the windows session storage | |
authToken.getToken = function() { | |
var deferred = $q.defer(); | |
/** your app's route to get a token, | |
* note that the user must be logged in, | |
* or must send their credentials in | |
* this request | |
*/ | |
$http.post('/gettoken', {}) | |
.success(function(data, status, headers, config) { | |
$window.sessionStorage.token = data.token; | |
deferred.resolve(); | |
}) | |
.error(function(data, status, headers, config) { | |
// Erase the token if the user fails to log in | |
delete $window.sessionStorage.token; | |
deferred.reject(); | |
}); | |
return deferred.promise; | |
}; | |
return authToken; | |
} | |
]) | |
.factory('authInterceptor', | |
['$rootScope', | |
'$q', | |
'$window', | |
'$injector', | |
function($rootScope, $q, $window, $injector) { | |
return { | |
request: function(config) { | |
config.headers = config.headers || {}; | |
if ($window.sessionStorage.token) { | |
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; | |
} | |
return config; | |
}, | |
//error responses | |
responseError: function(rejection) { | |
//expired token | |
if (rejection.data.status === 401 && rejection.data.message === 'jwt expired') { | |
var $http = $injector.get('$http'), | |
deferred = $q.defer(), | |
authToken = $injector.get('AuthToken'); | |
authToken | |
.getToken() | |
.then(function() { | |
console.log('retrying original request'); | |
console.dir(rejection.config); | |
//this repeats the request with the original parameters | |
return deferred.resolve($http(rejection.config)); | |
}); | |
return deferred.promise; | |
} else { | |
return $q.reject(rejection); | |
} | |
} | |
}; | |
} | |
]); | |
app.config(['$httpProvider', | |
function($httpProvider) { | |
$httpProvider.interceptors.push('authInterceptor'); | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment