Last active
April 13, 2020 15:58
-
-
Save Gid733/3749b188566657bc8182c25fe644a50e 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 { toast } from "react-toastify"; | |
import axios from "axios"; | |
import { getCurrentUser } from "../helpers/auth.helper"; | |
import { dispatch } from "../../redux/root.store"; | |
import { logoutUser } from "../../redux/actions/auth/auth.actions"; | |
export const axiosBase = axios.create(); | |
axiosBase.interceptors.request.use(function(request) { | |
debugger; | |
const currentUser = getCurrentUser(); | |
request.headers.Authorization = currentUser.isSignedIn | |
? `Bearer ${currentUser.accessToken}` | |
: ""; | |
return request; | |
}); | |
axiosBase.interceptors.response.use( | |
response => response, | |
error => { | |
if (error.response.status === 401) { | |
toast.warn("401 - Unauthorized"); | |
dispatch(logoutUser()); | |
} else if (error.response.status === 500) { | |
toast.error("500 - Network Error"); | |
} else { | |
error.response.data.errors.forEach(message => { | |
toast.error(message.errorMessage); | |
}); | |
} | |
return Promise.reject(error); | |
} | |
); | |
function extractData(response) { | |
response.data.messages.forEach(message => { | |
toast.success(message.messageText); | |
}); | |
return response.data; | |
} | |
/* eslint-disable */ | |
class ApiBase { | |
get(url, params, headers = {}) { | |
return axiosBase.get(url, { params, headers }).then(res => { | |
return extractData(res); | |
}); | |
} | |
post(url, body = null, headers = {}) { | |
return axiosBase.post(url, body, { headers }).then(res => { | |
return extractData(res); | |
}); | |
} | |
put(url, body = null, headers = {}) { | |
return axiosBase.put(url, body, { headers }).then(res => { | |
return extractData(res); | |
}); | |
} | |
delete(url, params, headers = {}) { | |
return axiosBase.delete(url, { params, headers }).then(res => { | |
return extractData(res); | |
}); | |
} | |
file(url, body = null, headers = {}) { | |
const formData = new FormData(); | |
formData.append("file", body); | |
return axiosBase | |
.post(url, formData, { responseType: "blob", headers: headers }) | |
.then(res => { | |
return extractData(res); | |
}); | |
} | |
} | |
export default new ApiBase(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment