Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import axios from 'axios';
import {newNotification} from 'actions/notifications';
import filterAxiosProps from './filter-axios-props';
export const FETCH_API_ERROR = 'FETCH_API_ERROR';
export const FETCH_API = 'FETCH_API';
function checkIfItIsFunction(notification, response) {
if (typeof notification === 'function') {
return notification(response);
}
return notification;
}
const apiMiddleware = (store) => (next) => (action) => {
const {dispatch} = store;
const fetchAPIAction = action[FETCH_API];
if (typeof fetchAPIAction === 'undefined') {
return next(action);
}
const {
types, successNotification, errorNotification,
onSuccess, onFailure,
} = fetchAPIAction;
const [REQUEST, SUCCESS, FAILURE] = types;
const axiosRequest = filterAxiosProps(fetchAPIAction);
const onAxiosSuccess = (response) => {
// If there is succes notification, dispatch it
if (successNotification) {
const noti = checkIfItIsFunction(successNotification, response);
dispatch(newNotification(noti));
}
next({type: SUCCESS, response});
if (onSuccess) {
onSuccess(response);
}
};
const onAxiosFailure = (response) => {
console.error(response);
if (errorNotification) {
const noti = checkIfItIsFunction(errorNotification, response);
dispatch(newNotification(noti));
}
dispatch({type: FETCH_API_ERROR, error: response.error});
next({type: FAILURE, response});
if (onFailure) {
onFailure(response);
}
};
// Dispatch REQUEST action
dispatch({type: REQUEST});
// Return Axios promise
return axios(axiosRequest)
.then(onAxiosSuccess, onAxiosFailure)
.catch((error) => {
console.error(error);
dispatch({type: FETCH_API_ERROR, error: error.message});
if (errorNotification) {
dispatch(newNotification({
level: 'error',
title: FETCH_API_ERROR,
message: error.message,
}));
}
});
};
export default apiMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.