54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
|
import {module} from '../module';
|
||
|
|
||
|
interceptor.$inject = ['$q', '$rootScope', '$window', 'vnApp', '$translate', '$cookies'];
|
||
|
function interceptor($q, $rootScope, $window, vnApp, $translate, $cookies) {
|
||
|
$rootScope.loading = false;
|
||
|
return {
|
||
|
request: function(config) {
|
||
|
$rootScope.loading = true;
|
||
|
let token = $cookies.get('vnToken');
|
||
|
|
||
|
if (token)
|
||
|
config.headers.Authorization = token;
|
||
|
|
||
|
return config;
|
||
|
},
|
||
|
requestError: function(rejection) {
|
||
|
return $q.reject(rejection);
|
||
|
},
|
||
|
response: function(response) {
|
||
|
switch (response.config.method) {
|
||
|
case 'PUT':
|
||
|
case 'POST':
|
||
|
case 'PATCH':
|
||
|
vnApp.showMessage($translate.instant('Data saved!'));
|
||
|
}
|
||
|
$rootScope.loading = false;
|
||
|
return response;
|
||
|
},
|
||
|
responseError: function(rejection) {
|
||
|
$rootScope.loading = false;
|
||
|
let data = rejection.data;
|
||
|
let error;
|
||
|
|
||
|
if (data && data.error instanceof Object)
|
||
|
error = data.error.message;
|
||
|
else if (rejection.status === -1)
|
||
|
error = $translate.instant(`Can't contact with server`);
|
||
|
else
|
||
|
error = `${rejection.status}: ${rejection.statusText}`;
|
||
|
|
||
|
if (rejection.status === 401) {
|
||
|
let location = $window.location;
|
||
|
let continueUrl = location.pathname + location.search + location.hash;
|
||
|
continueUrl = encodeURIComponent(continueUrl);
|
||
|
$window.location = `/auth/?apiKey=${vnApp.name}&continue=${continueUrl}`;
|
||
|
}
|
||
|
|
||
|
vnApp.showError(error);
|
||
|
return $q.reject(rejection);
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
module.factory('vnInterceptor', interceptor);
|