choko-org / redux-boot

Modular Redux bootstrap with asynchronous side-effects.
MIT License
126 stars 7 forks source link

Handle Middlewares function should use composed function #30

Closed sebas5384 closed 7 years ago

sebas5384 commented 7 years ago

Middlewares using handlers should had the possibility of declaring something before the dispatch cycle. For example:

const module = {
  middleware: {
    [HTTP_REQUEST]: store => {
      const db = dbConnect()
      return next => action => {
        // Do something with the "db" connection.
        return next(action)
      }
    }
  }
}

https://github.com/choko-org/redux-boot/blob/master/src/processModules.js#L33-L42

sebas5384 commented 7 years ago

Solution proposal:

export function handleMiddlewares(listeners) {
  return store => {
    const middlewares = Object.keys(listeners).map(type => {
      return { type, middleware: listeners[type](store) }
    })

    return next => action => {
      const matched = middlewares
        .filter(({ type }) => type === action.type)
        .shift()

      if (!matched) {
        return next(action)
      }

      return matched.middleware(next)(action)
    }
  }
}