Created
August 21, 2018 10:56
-
-
Save kaleem-elahi/b423abb45a69dc9d60ec402da118006a to your computer and use it in GitHub Desktop.
API manager
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 BASE_URL from './../constants'; | |
import { | |
showNotification, | |
} from '../utils/Notifications'; | |
function makeHeaders() { | |
let headerObj = {}; | |
if (JSON.parse(localStorage.getItem('user_info')) != null) { | |
const token = `Bearer ${JSON.parse(localStorage.getItem('user_info'))}`; | |
headerObj = { | |
Authorization: token, | |
}; | |
} | |
return headerObj; | |
} | |
const axiosApi = axios.create({ | |
withCredentials: true, | |
baseURL: `${BASE_URL}/`, | |
}); | |
axiosApi.interceptors.request.use((request) => { | |
// Only cache GET requests | |
if (request.method === 'get') { | |
let { | |
url, | |
} = request; | |
if (url.indexOf('?') > 0) url += `&random=${Math.random()}`; | |
else url += `?random=${Math.random()}`; | |
request.url = url; | |
} | |
request.headers = makeHeaders(); | |
return request; | |
}); | |
axiosApi.interceptors.response.use(response => response, (err) => { | |
if (err.response && err.response.status === 403) { | |
showNotification(err.response.data.msg, 'error', 5000); | |
} | |
return Promise.reject(err); | |
}); | |
export default axiosApi; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment