Skip to content

Instantly share code, notes, and snippets.

@VanDalkvist
Created December 17, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanDalkvist/3f51f3305bd0f6a466b19b7dbae2dc2d to your computer and use it in GitHub Desktop.
Save VanDalkvist/3f51f3305bd0f6a466b19b7dbae2dc2d to your computer and use it in GitHub Desktop.
Configurable fetch middleware implementation
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