Skip to content

Instantly share code, notes, and snippets.

@kaleem-elahi
Created August 21, 2018 10:56
Show Gist options
  • Save kaleem-elahi/b423abb45a69dc9d60ec402da118006a to your computer and use it in GitHub Desktop.
Save kaleem-elahi/b423abb45a69dc9d60ec402da118006a to your computer and use it in GitHub Desktop.
API manager
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