Last active
August 14, 2018 02:18
-
-
Save jpdillingham/e09e78fd2f14440197d49f924ac0627c to your computer and use it in GitHub Desktop.
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
import axios from 'axios'; | |
import { getCredentials, saveCredentials, deleteCredentials } from './credentialStore'; | |
import { API_ROOT } from './constants'; | |
axios.defaults.baseURL = API_ROOT; | |
const api = axios.create(); | |
api.interceptors.request.use(config => { | |
let creds = getCredentials(); | |
config.headers['Content-Type'] = 'application/json'; | |
if (creds && creds.accessToken) { | |
config.headers.Authorization = creds.tokenType + ' ' + creds.accessToken; | |
} | |
return config; | |
}); | |
api.interceptors.response.use(config => { | |
return config; | |
}, error => { | |
let request = error.config; | |
let creds = getCredentials(); | |
if (error.response.status === 401 && !request.retrying && creds && creds.refreshToken) { | |
request.retrying = true; | |
let data = JSON.stringify(creds.refreshToken); | |
let headers = { headers: { 'Content-Type': 'application/json' }}; | |
return axios.post('/v1/tokens/refresh', data, headers) | |
.then(response => { | |
saveCredentials(response.data); | |
request.headers.Authorization = response.data.tokenType + ' ' + response.data.accessToken; | |
return axios(request); | |
}, error => { | |
deleteCredentials(); | |
window.location.reload(true); | |
return Promise.reject(error); | |
} | |
); | |
} | |
else { | |
return Promise.reject(error); | |
} | |
}) | |
export default api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment