Skip to content

Instantly share code, notes, and snippets.

@cchamberlain
Created April 5, 2016 05:56
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 cchamberlain/22ff1af8a9cec6a4ef6626415dcbea43 to your computer and use it in GitHub Desktop.
Save cchamberlain/22ff1af8a9cec6a4ef6626415dcbea43 to your computer and use it in GitHub Desktop.
redux-middleware
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()
/**
* 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