Created
April 5, 2016 05:56
-
-
Save cchamberlain/22ff1af8a9cec6a4ef6626415dcbea43 to your computer and use it in GitHub Desktop.
redux-middleware
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 timeoutScheduler from './timeoutScheduler' | |
import identityHandler from './identityHandler' | |
import apiDispatcher from './apiDispatcher' | |
import routeHandler from './routeHandler' | |
import idleHandler from './idleHandler' | |
import errorHandler from './errorHandler' | |
/** | |
* Lets you dispatch special actions with a { meta } field. | |
* | |
* This middleware will chain through all middleware specified in metaMap in | |
* order and return the result. | |
*/ | |
export const createMetaRouter = (metaMap = new Map( [ [ 'delay', timeoutScheduler ] | |
, [ 'identity', identityHandler ] | |
, [ 'api', apiDispatcher ] | |
, [ 'route', routeHandler ] | |
, [ 'idle', idleHandler] | |
, [ 'err', errorHandler ] | |
] )) => store => next => action => { | |
if(!action.meta) | |
return next(action) | |
const supportedTypes = metaMap.keys() | |
const metaTypes = Object.keys(action.meta) | |
let result = metaTypes.filter(x => supportedTypes.includes(x)) | |
.map(x => metaMap.get(x)) | |
.reduce((last, middleware) => middleware(last), action) | |
return next(result) | |
} | |
export default createMetaRouter() |
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
/** | |
* Schedules actions with { meta: { delay: N } } to be delayed by N milliseconds. | |
* Makes `dispatch` return a function to cancel the timeout in this case. | |
*/ | |
const timeoutScheduler = store => next => action => { | |
if (!action.meta || !action.meta.delay) { | |
return next(action) | |
} | |
let timeoutId = setTimeout( | |
() => next(action), | |
action.meta.delay | |
) | |
return function cancel() { | |
clearTimeout(timeoutId) | |
} | |
} | |
export default timeoutScheduler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment