Skip to content

Instantly share code, notes, and snippets.

@AlexKott
Created September 10, 2018 07:20
Show Gist options
  • Save AlexKott/d0b36882e873ec931d69f5d9cc2c7e7f to your computer and use it in GitHub Desktop.
Save AlexKott/d0b36882e873ec931d69f5d9cc2c7e7f to your computer and use it in GitHub Desktop.
Example of a more complex request middleware
import * as t from '@/actions/types';
import ajax from '@/adapters';
import getEndpoint from '@/constants/endpoints';
export default store => next => async action => {
const { type, payload } = action;
if (type === t.SEND_REQUEST) {
const {
data,
entity,
method,
name,
onSuccess = [],
onError = [],
onFinally = [],
} = payload;
const { headers, url } = getEndpoint(name, entity);
const token = getAuthToken(store.getState());
try {
const response = await ajax({
data,
headers,
method,
token,
url,
});
onSuccess.forEach(method => method(response));
} catch(error) {
onError.forEach(method => method(error));
} finally {
onFinally.forEach(method => method());
}
}
next(action);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment