salix/front/core/services/interceptor.js

51 lines
1.5 KiB
JavaScript

import ngModule from '../module';
import HttpError from 'core/lib/http-error';
interceptor.$inject = ['$q', 'vnApp', '$translate'];
function interceptor($q, vnApp, $translate) {
let apiPath = 'api/';
let token;
return {
setToken(newToken) {
token = newToken;
},
setApiPath(path) {
apiPath = path;
},
request(config) {
vnApp.pushLoader();
if (config.url.charAt(0) !== '/' && apiPath)
config.url = `${apiPath}${config.url}`;
if (token)
config.headers.Authorization = token;
if ($translate.use())
config.headers['Accept-Language'] = $translate.use();
if (config.filter) {
if (!config.params) config.params = {};
config.params.filter = config.filter;
}
return config;
},
requestError(rejection) {
return $q.reject(rejection);
},
response(response) {
vnApp.popLoader();
const newVersion = response.headers('salix-version');
vnApp.setVersion(newVersion);
return response;
},
responseError(rejection) {
vnApp.popLoader();
const err = new HttpError(rejection.statusText);
Object.assign(err, rejection);
return $q.reject(err);
},
};
}
ngModule.factory('vnInterceptor', interceptor);