Created
August 29, 2015 19:57
-
-
Save leafmind/499575ed5f874887a8bd to your computer and use it in GitHub Desktop.
This file contains 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
export function promiseMiddleware() { | |
function isPromise(value) { | |
return value && typeof value.then === 'function'; | |
} | |
return next => action => { | |
if (!isPromise(action.promise)) { | |
return next(action); | |
} | |
const { types } = action; | |
const promise = action.promise; | |
const [ PENDING, FULFILLED, REJECTED ] = types; | |
/** | |
* Dispatch the first async handler. This tells the | |
* reducer that an async action has been dispatched. | |
*/ | |
next({ | |
type: PENDING | |
}); | |
/** | |
* Return either the fulfilled action object or the rejected | |
* action object. | |
*/ | |
return promise.then( | |
response => next({ | |
response: JSON.parse(response.text).data || JSON.parse(response.text), | |
type: FULFILLED | |
}), | |
error => next({ | |
error: JSON.parse(error.response.text).error, | |
type: REJECTED | |
}) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment