Skip to content

Instantly share code, notes, and snippets.

@robshep
Last active August 29, 2015 14:23
Show Gist options
  • Save robshep/e906dd8902986f05154c to your computer and use it in GitHub Desktop.
Save robshep/e906dd8902986f05154c to your computer and use it in GitHub Desktop.
Common AngularJS HTTP configurations
/**
* @author Rob Shepherd
*/
'use strict';
;(function(){
angular.module('sbHttpConfig', [])
.factory('httpRedirectionInterceptor', ['$location', function($location) {
return {
'response': function(response) {
var nextUri = response.headers("X-WebClient-NextURI");
if(!!(nextUri)){
if(nextUri.indexOf("/") == 0){
window.location.href = nextUri;
}
}
if(!!(response) && !!(response.data) && response.data.hasOwnProperty("redirect")){
window.location.href = response.data.redirect;
return null;
}
else {
return response;
}
}
};
}])
.factory('httpOKButErrorWritingInterceptor', ['$location', function($location) {
return {
'response': function(response) {
if( (!!(response.data.type)) && response.data.type == "OKButErrorWriting"){
PNotify.err("Your thing was saved, but something bad happened when responding. try refreshing the page");
response.data = null;
}
return response;
}
};
}])
.factory('httpErrorNotificationInterceptor', ['$q', function($q) {
return {
'responseError': function(response) {
if( !!(response.config.nowarn) ){
return $q.reject(response);
}
var data = response.data;
if(!data){
PNotify.err(response.statusText);
}
else if(typeof data == 'string'){
PNotify.err(data);
}
else if(angular.isArray()){
var txt = "";
for(var i=0;i<data.length;i++ ){
txt = txt + "<strong>" + i + "</strong>: " + data[i] + "<br>";
}
PNotify.err(txt);
}
else if( data.hasOwnProperty("errors")){
var txt = "";
for(var i=0;i<data.errors.length;i++){
var error = data.errors[i];
txt = txt + "<strong>" + error.field + " " + error.defaultMessage + "</strong><br>";
}
PNotify.err(txt);
}
else {
var txt = "";
for(var propertyName in data ){
if(data.hasOwnProperty(propertyName)){
txt = txt + "<strong>" + propertyName + "</strong>: " + data[propertyName] + "<br>";
}
}
PNotify.err(txt);
}
return $q.reject(response);
}
};
}])
.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('httpRedirectionInterceptor');
$httpProvider.interceptors.push('httpErrorNotificationInterceptor');
$httpProvider.interceptors.push('httpOKButErrorWritingInterceptor');
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment