Skip to content

Instantly share code, notes, and snippets.

@guilhermepontes
Last active April 28, 2020 18:07
Show Gist options
  • Save guilhermepontes/4c244584a9c361ef0302afaf5ee4ec9b to your computer and use it in GitHub Desktop.
Save guilhermepontes/4c244584a9c361ef0302afaf5ee4ec9b to your computer and use it in GitHub Desktop.
function httpAction(action) {
const httpActionTemplate = {
type: "",
endpoint: null,
verb: "GET",
payload: null,
headers: [],
}
return {
HTTP_ACTION: { ...httpActionTemplate, ...action }
}
}
const httpMiddleware = store => next => async action => {
const actionTypesSuffixes = {
pending: "_PENDING",
fullfilled: "_FULFILLED",
rejected: "_REJECTED",
}
if (!action[HTTP_ACTION]) return next(action)
const actionInfo = action[HTTP_ACTION]
const fetchOptions = {
method: actionInfo.verb,
headers: actionInfo.headers,
body: actionInfo.payload || null,
}
next({
type: actionInfo.type + actionTypesSuffixes.pending
})
try {
const request = await fetch(actionInfo.endpoint, fetchOptions)
const response = await response.json()
next({
type: actionInfo.type + actionTypesSuffixes.fulfilled,
payload: response,
})
} catch (error)
next({
type: actionInfo.type + actionTypesSuffixes.rejected,
payload: error,
}))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment