Last active
April 28, 2020 18:07
-
-
Save guilhermepontes/4c244584a9c361ef0302afaf5ee4ec9b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function httpAction(action) { | |
const httpActionTemplate = { | |
type: "", | |
endpoint: null, | |
verb: "GET", | |
payload: null, | |
headers: [], | |
} | |
return { | |
HTTP_ACTION: { ...httpActionTemplate, ...action } | |
} | |
} |
This file contains hidden or 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
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