import axios from 'axios';
import config from '../../configuration.json';
import qs from 'qs';
const baseURL = config['baseUrl_local'];
let authTokenRequest;
var client = axios.create({
baseURL: baseURL,
headers: {
appID: 8,
version: "1.1.0",
empID: localStorage.getItem('empID'),
token: localStorage.getItem('accessToken')
}
});
function getAuthToken() {
if (!authTokenRequest) {
authTokenRequest = requestNewToken();
authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
}
return authTokenRequest;
}
function requestNewToken() {
var newToken = request({
method: "post",
url: '/sign-in',
data: qs.stringify({
"userName":localStorage.getItem('userName'),
"password":localStorage.getItem('password')
})
}).then((res)=>{
if(res.status == "success"){
localStorage.setItem('accessToken',res.data.accessToken);
featureArray in local storage
if(res.data.features){
localStorage.setItem(
'featureArray',
JSON.stringify(res.data.features));
}
client = axios.create({
baseURL: baseURL,
headers: {
appID: 8,
version: "1.1.0",
empID: localStorage.getItem('empID'),
token: localStorage.getItem('accessToken')
}
});
} else {
window.location = "/logout";
}
});
return newToken;
}
function resetAuthTokenRequest() {
authTokenRequest = null;
}
client.interceptors.response.use(undefined, err => {
const error = err.response;
if (error.status===401 && error.config &&
!error.config.__isRetryRequest) {
return getAuthToken().then(response => {
error.config.__isRetryRequest = true;
error.config.headers.token= localStorage.getItem("accessToken");
return client(error.config);
});
}
});
const request = function(options) {
const onSuccess = function(response) {
return response.data;
}
const onError = function(error) {
if (error.response) {
} else {
console.error('Error Message:', error.message);
}
return Promise.reject(error.response || error.message);
}
return client(options)
.then(onSuccess)
.catch(onError);
options
}
export default request;