Created
October 24, 2017 09:01
-
-
Save msmaromi/f8c273149d19565d0079bc13a80daf46 to your computer and use it in GitHub Desktop.
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
import { RECEIVE_ERROR } from '../core/Constants' | |
import { | |
REQUEST_GET, | |
REQUEST_GET_ONE, | |
REQUEST_POST, | |
REQUEST_PATCH, | |
REQUEST_PUT, | |
REQUEST_DELETE | |
} from '../core/RequestConstants' | |
import { handleError } from '../actions/app' | |
const callAPI = (type, endpoint, params) => { | |
switch (type) { | |
case REQUEST_GET: | |
if (params) return endpoint.getAll(params) // params exist | |
else return endpoint.getAll() // no params | |
break; | |
case REQUEST_GET_ONE: | |
if (params) return endpoint.get(params) | |
else return endpoint.get() | |
break; | |
case REQUEST_POST: | |
if (params) return endpoint.post(params) | |
else return endpoint.post() | |
break; | |
case REQUEST_PATCH: | |
if (params) return endpoint.patch(params) | |
else return endpoint.patch() | |
break; | |
case REQUEST_PUT: | |
if (params) return endpoint.put(params) | |
else return endpoint.put() | |
break; | |
case REQUEST_DELETE: | |
if (params) return endpoint.delete(params) | |
else return endpoint.delete() | |
break; | |
default: | |
if (params) return endpoint.getAll(params) // params exist | |
else return endpoint.getAll() // no params | |
} | |
} | |
const apiMiddleware = ({dispatch, getState}) => { | |
return next => action => { | |
const { type, endpoint, request, params, payload } = action | |
// normal action, pass it on | |
if (!endpoint) return next(action) | |
dispatch({ | |
type, | |
status: 'request', | |
payload | |
}) | |
return new Promise(function(resolve, reject) { | |
callAPI(request, endpoint, params) | |
.then(response => { | |
resolve(response) | |
return dispatch({ | |
type, | |
status: 'success', | |
response, | |
payload | |
}) | |
}, error => { | |
reject(error) | |
dispatch({ | |
type, | |
status: 'error' | |
}); | |
return dispatch(handleError(error)) | |
}) | |
}); | |
} | |
} | |
export default apiMiddleware |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment