Skip to content

Instantly share code, notes, and snippets.

@benthehenten
Last active August 15, 2020 16:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benthehenten/06b3b910d08bd2fc206fa221d8e2722e to your computer and use it in GitHub Desktop.
Save benthehenten/06b3b910d08bd2fc206fa221d8e2722e to your computer and use it in GitHub Desktop.
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;
@AdamZaczek
Copy link

AdamZaczek commented Jun 24, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment