Skip to content

Commit

Permalink
possibility use many instances [#5]
Browse files Browse the repository at this point in the history
  • Loading branch information
pofigizm committed Aug 28, 2018
1 parent 3cd7e12 commit b81be4d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 22 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "redux-dynamic-middlewares",
"version": "0.5.0",
"version": "0.6.0",
"description": "Allow add or remove redux middlewares dynamically",
"main": "lib/index.js",
"scripts": {
Expand Down
56 changes: 36 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,53 @@
import { compose } from 'redux'

let allDynamicMiddlewares = []
const createDynamicMiddlewares = () => {
let allDynamicMiddlewares = []

const dynamicMiddlewares = store => next => (action) => {
const chain = allDynamicMiddlewares.map(middleware => middleware(store))
const enhancer = store => next => (action) => {
const chain = allDynamicMiddlewares.map(middleware => middleware(store))

return compose(...chain)(next)(action)
}
return compose(...chain)(next)(action)
}

const addMiddleware = (...middlewares) => {
allDynamicMiddlewares = [...allDynamicMiddlewares, ...middlewares]
}
const addMiddleware = (...middlewares) => {
allDynamicMiddlewares = [...allDynamicMiddlewares, ...middlewares]
}

const removeMiddleware = (middleware) => {
const index = allDynamicMiddlewares.findIndex(d => d === middleware)
const removeMiddleware = (middleware) => {
const index = allDynamicMiddlewares.findIndex(d => d === middleware)

if (index === -1) {
// eslint-disable-next-line no-console
console.error('Middleware does not exist!', middleware)
if (index === -1) {
// eslint-disable-next-line no-console
console.error('Middleware does not exist!', middleware)

return
return
}

allDynamicMiddlewares = allDynamicMiddlewares.filter((_, mdwIndex) => mdwIndex !== index)
}

allDynamicMiddlewares = allDynamicMiddlewares.filter((_, mdwIndex) => mdwIndex !== index)
}
const resetMiddlewares = () => {
allDynamicMiddlewares = []
}

const resetMiddlewares = () => {
allDynamicMiddlewares = []
return {
enhancer,
addMiddleware,
removeMiddleware,
resetMiddlewares,
}
}

export default dynamicMiddlewares
export {
const dynamicMiddlewaresInstance = createDynamicMiddlewares()

export default dynamicMiddlewaresInstance.enhancer

export const {
addMiddleware,
removeMiddleware,
resetMiddlewares,
} = dynamicMiddlewaresInstance

export {
createDynamicMiddlewares,
}

0 comments on commit b81be4d

Please sign in to comment.