Skip to content

Instantly share code, notes, and snippets.

@trubachev
Created October 6, 2019 23:20
Show Gist options
  • Save trubachev/7c6fb79173fd86c4e33ee24e92242d5d to your computer and use it in GitHub Desktop.
Save trubachev/7c6fb79173fd86c4e33ee24e92242d5d to your computer and use it in GitHub Desktop.
const API_TYPE_REGEX = /API_[^_]*$/
const notApiAction = type => !API_TYPE_REGEX.test(type)
const host = "https://www.izettle.com/starwars"
const handleResponse = res => {
if (res.status <= 400 && res.status >= 200) {
return res.json()
}
throw res.status
}
const onSuccess = (dispatch, type) => jsonData =>
dispatch({
type: `${type}_SUCCESS`,
payload: jsonData,
})
const onError = (dispatch, type) => error =>
dispatch({
type: `${type}_FAILURE`,
payload: error,
})
export default ({ dispatch }) => next => async action => {
next(action)
const { type, payload } = action
if (notApiAction(type)) {
return
}
const url = `${host}${payload.url}`
const { method, body } = payload
fetch(url, {
method: method || "GET",
body: body && JSON.stringify(body),
})
.then(handleResponse)
.then(onSuccess(dispatch, type))
.catch(onError(dispatch, type))
dispatch({ type: `${type}_PENDING` })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment