Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ const isArray = type => Array.isArray(type)

const isFunc = val => typeof val === 'function'

/**
* Factory to create action dispatchers
* @param {Function} dispatch - the store dispatcher
* @param {Function} fn - the redux action to be dispatched
* @returns {Function} a function that dispatch data through the redux action
*/
const createDispatcher = (dispatch, fn) => data => { dispatch(fn(data)) }

export default function(store) {
const {dispatch} = store

Expand All @@ -12,17 +20,27 @@ export default function(store) {
return next(action)
}

const [requesting, success, failure] = type

dispatch(requesting())

const request = payload.data()

return isFunc(request.then)
? request.then(
response => dispatch(success({...payload, data: response.data})),
error => dispatch(failure({payload: error, error: true}))
)
: next(action)
const [
requestingAction,
successAction,
failureAction
] = type

const requestingDispatcher = createDispatcher(dispatch, requestingAction);
const failureDispatcher = createDispatcher(dispatch, failureAction);
const successDispatcher = createDispatcher(dispatch, successAction);

const { data:request } = payload;

return
isFunc(request.then)
?
Promise.resolve()
.then(requestingDispatcher) // pass the result of requesting action to promise chain
.then(request) // do the user request call
.then(successDispatcher) // pass the success action
.catch(failureDispatcher) // in case of failure of any item in the chain, pass through failure action
:
next(action)
}
}