Last active
August 15, 2020 16:02
-
-
Save benthehenten/06b3b910d08bd2fc206fa221d8e2722e 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 { API } from "../actions/types"; | |
import { accessDenied, apiError, apiStart, apiEnd } from "../actions/api"; | |
const apiMiddleware = ({ dispatch }) => next => action => { | |
next(action); | |
if (action.type !== API) return; | |
const { | |
url, | |
method, | |
data, | |
accessToken, | |
onSuccess, | |
onFailure, | |
label, | |
headers | |
} = action.payload; | |
const dataOrParams = ["GET", "DELETE"].includes(method) ? "params" : "data"; | |
// axios default configs | |
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL || ""; | |
axios.defaults.headers.common["Content-Type"]="application/json"; | |
axios.defaults.headers.common["Authorization"] = `Bearer${token}`; | |
if (label) { | |
dispatch(apiStart(label)); | |
} | |
axios | |
.request({ | |
url, | |
method, | |
headers, | |
[dataOrParams]: data | |
}) | |
.then(({ data }) => { | |
dispatch(onSuccess(data)); | |
}) | |
.catch(error => { | |
dispatch(apiError(error)); | |
dispatch(onFailure(error)); | |
if (error.response && error.response.status === 403) { | |
dispatch(accessDenied(window.location.pathname)); | |
} | |
}) | |
.finally(() => { | |
if (label) { | |
dispatch(apiEnd(label)); | |
} | |
}); | |
}; | |
export default apiMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm surprised this has no comments yet. Amazing job! I'm doing a similar thing in graphql and this snippet has been very useful as a reference.