diff --git a/src/defaults.js b/src/defaults.js new file mode 100644 index 0000000..93302a6 --- /dev/null +++ b/src/defaults.js @@ -0,0 +1,6 @@ +const defaults = { + ok: res => res.ok, + fetch +}; + +export default defaults; diff --git a/src/index.js b/src/index.js index 680ac14..0c2f082 100644 --- a/src/index.js +++ b/src/index.js @@ -33,7 +33,7 @@ import RSAA from './RSAA'; import { isRSAA, validateRSAA, isValidRSAA } from './validation'; import { InvalidRSAA, InternalError, RequestError, ApiError } from './errors'; import { getJSON } from './util'; -import { apiMiddleware } from './middleware'; +import { apiMiddleware, createMiddleware } from './middleware'; export { // Alias RSAA to CALL_API to smooth v1 - v2 migration @@ -48,5 +48,6 @@ export { RequestError, ApiError, getJSON, + createMiddleware, apiMiddleware }; diff --git a/src/middleware.js b/src/middleware.js index d9b1a89..5b37c35 100644 --- a/src/middleware.js +++ b/src/middleware.js @@ -2,15 +2,12 @@ import RSAA from './RSAA'; import { isRSAA, validateRSAA } from './validation'; import { InvalidRSAA, RequestError } from './errors'; import { normalizeTypeDescriptors, actionWith } from './util'; +import defaults from './defaults'; -/** - * A Redux middleware that processes RSAA actions. - * - * @type {ReduxMiddleware} - * @access public - */ -function apiMiddleware({ getState }) { - return next => action => { +function createMiddleware(options = {}) { + const middlewareOptions = Object.assign({}, defaults, options); + + return ({ getState }) => next => action => { // Do not process actions without an [RSAA] property if (!isRSAA(action)) { return next(action); @@ -42,7 +39,8 @@ function apiMiddleware({ getState }) { body, headers, options = {}, - fetch: doFetch = fetch + fetch: doFetch = middlewareOptions.fetch, + ok = middlewareOptions.ok } = callAPI; const { method, credentials, bailout, types } = callAPI; const [requestType, successType, failureType] = normalizeTypeDescriptors( @@ -176,7 +174,7 @@ function apiMiddleware({ getState }) { } // Process the server response - if (res.ok) { + if (ok(res)) { return next(await actionWith(successType, [action, getState(), res])); } else { return next( @@ -193,4 +191,14 @@ function apiMiddleware({ getState }) { }; } -export { apiMiddleware }; +/** + * A Redux middleware that processes RSAA actions. + * + * @type {ReduxMiddleware} + * @access public + */ +function apiMiddleware({ getState }) { + return createMiddleware()({ getState }); +} + +export { createMiddleware, apiMiddleware };