Last active
May 30, 2016 06:21
-
-
Save kadmil/72700a3a6934b02322abaed19910f6a4 to your computer and use it in GitHub Desktop.
API middleware
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
export const apiMiddleware = store => next => action => { | |
//use destructuring to get apiCall and request from action object | |
const {apiCall, request, ...actualAction} = action | |
//ignore normal actions | |
if (!apiCall) { | |
return next(action) | |
} | |
//dispatch request_begin action — maybe we'd like some loaders | |
//note no apiCall and request fields here — with them middleware will have an endless cycle | |
store.dispatch({...actualAction, type: `${action.type}_REQUEST`}) | |
//actually fire a request | |
apiCall(request) | |
.then(apiResponse => apiResponse.json().then(response => { | |
if (apiResponse.status === 200) { | |
//all fine, fire action with response | |
return store.dispatch({response, request, type: `${action.type}_RESPONSE`}); | |
} else { | |
//something went wrong, fire action with error | |
return store.dispatch({error: response, request, type: `${action.type}_FAIL`}); | |
} | |
})) | |
.catch(error => { | |
//error during request, something with API or network or whatever | |
store.dispatch({type: 'REQUEST_ERROR', error}) | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment