Created
December 17, 2018 11:45
-
-
Save VanDalkvist/3f51f3305bd0f6a466b19b7dbae2dc2d to your computer and use it in GitHub Desktop.
Configurable fetch middleware implementation
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
import buildAsyncStages from "../stages/async-stages"; | |
import { handleFetchError } from "../errors"; | |
const ASYNC_FETCH = "ASYNC_FETCH"; | |
const baseRequestOptions = { credentials: "same-origin" }; | |
const fetchMiddleware = fetchImplementation => store => next => action => { | |
next(action); | |
if (action.type !== ASYNC_FETCH) return; | |
const responseDescription = action.response || {}; | |
const customMappings = responseDescription.mappings || {}; | |
const mappings = { | |
failure: res => ({ error: res && res.message }), | |
...customMappings | |
}; | |
const stageBuilderArgs = [action.id, action.args, mappings]; | |
const stages = buildAsyncStages(...stageBuilderArgs)(store.dispatch); | |
const requestDescription = action.request; | |
const fetchRequest = new Request(requestDescription.url, { | |
...baseRequestOptions, | |
...requestDescription.options | |
}); | |
stages.begin(); | |
return fetchImplementation(fetchRequest) | |
.then(handleFetchError) | |
.then(res => res.json()) | |
.then(res => stages.success(res)) | |
.catch(error => stages.failure(error)); | |
}; | |
export { ASYNC_FETCH }; | |
export default fetchMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment