Skip to content

Instantly share code, notes, and snippets.

@javilobo8
Created January 8, 2018 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javilobo8/f1fbbd48e914f940f1b61ab12d38c6ca to your computer and use it in GitHub Desktop.
Save javilobo8/f1fbbd48e914f940f1b61ab12d38c6ca to your computer and use it in GitHub Desktop.
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