Skip to content

Commit 4c071c2

Browse files
feat(middleware): support enable/disable sepecific middleware (#160)
* fix(ts): fix build error * feat(middleware): support enable/disable sepecific middleware * test(middleware): add test for middleware config * fix(type): fix logger.enable return type
1 parent a830970 commit 4c071c2

File tree

6 files changed

+107
-50
lines changed

6 files changed

+107
-50
lines changed

README.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -665,13 +665,13 @@ export default connect(
665665
Just remove consoleDebugger middleware.
666666
667667
```typescript
668-
import { actionMiddlewares } from 'react-model'
668+
import { middlewares } from 'react-model'
669669
// Find the index of middleware
670-
const consoleDebuggerMiddlewareIndex = actionMiddlewares.indexOf(
671-
middlewares.consoleDebugger
672-
)
673-
// Remove it
674-
actionMiddlewares.splice(consoleDebuggerMiddlewareIndex, 1)
670+
671+
// Disable all actions' log
672+
middlewares.config.logger.enable = false
673+
// Disable logs from specific type of actions
674+
middlewares.config.logger.enable = ({ actionName }) => ['increment'].indexOf(actionName) !== -1
675675
```
676676
677677
[⇧ back to top](#table-of-contents)

__test__/disable-dubugger.spec.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// @ts-ignore
2+
/// <reference path="./index.d.ts" />
3+
import { Model, middlewares } from '../src'
4+
import { Counter } from '.'
5+
import { renderHook } from '@testing-library/react-hooks'
6+
7+
middlewares.config.logger.enable = ({ actionName }) =>
8+
['increment'].indexOf(actionName) !== -1
9+
10+
describe('PubSub', () => {
11+
test('run callback when specific action run', async () => {
12+
let actions: any
13+
let count = 0
14+
const { useStore, subscribe } = Model({ Counter })
15+
subscribe('Counter', 'increment', () => (count += 1))
16+
subscribe('Counter', 'add', () => (count += 10))
17+
renderHook(() => {
18+
;[, actions] = useStore('Counter')
19+
})
20+
await actions.increment()
21+
await actions.add(1)
22+
await actions.increment()
23+
await actions.increment()
24+
expect(count).toBe(13)
25+
})
26+
})

package.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-model",
3-
"version": "3.1.1",
3+
"version": "3.1.2",
44
"description": "The State management library for React",
55
"main": "./dist/react-model.js",
66
"umd:main": "./dist/react-model.umd.js",
@@ -20,8 +20,8 @@
2020
"immer": "^6.0.0"
2121
},
2222
"peerDependencies": {
23-
"react": "^16.3.0",
24-
"react-dom": "^16.3.0"
23+
"react": ">=16.3.0",
24+
"react-dom": ">=16.3.0"
2525
},
2626
"devDependencies": {
2727
"@commitlint/cli": "^8.1.0",
@@ -44,7 +44,7 @@
4444
"react-dom": "^16.8.4",
4545
"react-test-renderer": "^16.8.6",
4646
"remark-cli": "^8.0.0",
47-
"remark-lint": "^7.0.0",
47+
"remark-lint": "^7.0.0",
4848
"remark-preset-lint-recommended": "^4.0.0",
4949
"ts-jest": "^25.1.0",
5050
"tslint": "^5.14.0",

src/helper.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,11 @@ const setPartialState = (
5858
if (typeof partialState === 'function') {
5959
let state = Global.State[name]
6060
state = produce(state, partialState)
61-
Global.State = produce(Global.State, s => {
61+
Global.State = produce(Global.State, (s) => {
6262
s[name] = state
6363
})
6464
} else {
65-
Global.State = produce(Global.State, s => {
65+
Global.State = produce(Global.State, (s) => {
6666
s[name] = {
6767
...s[name],
6868
...partialState
@@ -73,20 +73,20 @@ const setPartialState = (
7373
}
7474

7575
const timeout = <T>(ms: number, data: T): Promise<T> =>
76-
new Promise(resolve =>
76+
new Promise((resolve) =>
7777
setTimeout(() => {
7878
console.log(ms)
7979
resolve(data)
8080
}, ms)
8181
)
8282

83-
const getInitialState = async <T extends any>(
83+
const getInitialState = async <T extends { modelName: string }>(
8484
context?: T,
8585
config?: { isServer?: boolean }
8686
) => {
8787
const ServerState: { [name: string]: any } = { __FROM_SERVER__: true }
8888
await Promise.all(
89-
Object.keys(Global.State).map(async modelName => {
89+
Object.keys(Global.State).map(async (modelName) => {
9090
if (
9191
!context ||
9292
!context.modelName ||

src/index.d.ts

+8
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,14 @@ type Context<S = {}> = InnerContext<S> & {
9494

9595
type Middleware<S = {}> = (C: Context<S>, M: Middleware<S>[]) => void
9696

97+
type MiddlewareConfig = {
98+
logger: {
99+
enable: boolean | ((context: BaseContext) => boolean)
100+
}
101+
devtools: { enable: boolean }
102+
tryCatch: { enable: boolean }
103+
}
104+
97105
interface Models<State = any, ActionKeys = any, ExtContext extends {} = {}> {
98106
[name: string]:
99107
| ModelType<State, ActionKeys, ExtContext>

src/middlewares.ts

+58-35
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,25 @@
11
import { getCache, setPartialState, timeout } from './helper'
22
// -- Middlewares --
33

4+
const config: MiddlewareConfig = {
5+
logger: {
6+
enable: process.env.NODE_ENV !== 'production'
7+
},
8+
devtools: {
9+
enable: process.env.NODE_ENV !== 'production'
10+
},
11+
tryCatch: {
12+
enable: process.env.NODE_ENV === 'production'
13+
}
14+
}
15+
416
const tryCatch: Middleware = async (context, restMiddlewares) => {
517
const { next } = context
6-
await next(restMiddlewares).catch((e: any) => console.log(e))
18+
if (config.tryCatch.enable) {
19+
await next(restMiddlewares).catch((e: any) => console.log(e))
20+
} else {
21+
await next(restMiddlewares)
22+
}
723
}
824

925
const getNewState: Middleware = async (context, restMiddlewares) => {
@@ -78,37 +94,46 @@ const subscription: Middleware = async (context, restMiddlewares) => {
7894

7995
const consoleDebugger: Middleware = async (context, restMiddlewares) => {
8096
const { Global } = context
81-
console.group(
82-
`%c ${
83-
context.modelName
84-
} State Change %c ${new Date().toLocaleTimeString()}`,
85-
'color: gray; font-weight: lighter;',
86-
'color: black; font-weight: bold;'
87-
)
88-
console.log(
89-
'%c Previous',
90-
`color: #9E9E9E; font-weight: bold`,
91-
Global.State[context.modelName]
92-
)
93-
console.log(
94-
'%c Action',
95-
`color: #03A9F4; font-weight: bold`,
96-
context.actionName,
97-
`payload: ${context.params}`
98-
)
99-
await context.next(restMiddlewares)
100-
console.log(
101-
'%c Next',
102-
`color: #4CAF50; font-weight: bold`,
103-
Global.State[context.modelName]
104-
)
105-
console.groupEnd()
97+
98+
if (
99+
config.logger.enable === true ||
100+
(typeof config.logger.enable === 'function' &&
101+
config.logger.enable(context))
102+
) {
103+
console.group(
104+
`%c ${
105+
context.modelName
106+
} State Change %c ${new Date().toLocaleTimeString()}`,
107+
'color: gray; font-weight: lighter;',
108+
'color: black; font-weight: bold;'
109+
)
110+
console.log(
111+
'%c Previous',
112+
`color: #9E9E9E; font-weight: bold`,
113+
Global.State[context.modelName]
114+
)
115+
console.log(
116+
'%c Action',
117+
`color: #03A9F4; font-weight: bold`,
118+
context.actionName,
119+
`payload: ${context.params}`
120+
)
121+
await context.next(restMiddlewares)
122+
console.log(
123+
'%c Next',
124+
`color: #4CAF50; font-weight: bold`,
125+
Global.State[context.modelName]
126+
)
127+
console.groupEnd()
128+
} else {
129+
await context.next(restMiddlewares)
130+
}
106131
}
107132

108133
const devToolsListener: Middleware = async (context, restMiddlewares) => {
109134
const { Global } = context
110135
await context.next(restMiddlewares)
111-
if (Global.withDevTools) {
136+
if (Global.withDevTools && config.devtools.enable) {
112137
Global.devTools.send(
113138
`${context.modelName}_${context.actionName}`,
114139
Global.State
@@ -137,20 +162,17 @@ const communicator: Middleware = async (context, restMiddlewares) => {
137162
await next(restMiddlewares)
138163
}
139164

140-
let actionMiddlewares = [
165+
const actionMiddlewares = [
166+
tryCatch,
167+
consoleDebugger,
168+
devToolsListener,
141169
getNewState,
142170
setNewState,
143171
stateUpdater,
144172
communicator,
145173
subscription
146174
]
147175

148-
if (process.env.NODE_ENV === 'production') {
149-
actionMiddlewares = [tryCatch, ...actionMiddlewares]
150-
} else {
151-
actionMiddlewares = [consoleDebugger, devToolsListener, ...actionMiddlewares]
152-
}
153-
154176
const middlewares = {
155177
communicator,
156178
consoleDebugger,
@@ -160,7 +182,8 @@ const middlewares = {
160182
setNewState,
161183
stateUpdater,
162184
subscription,
163-
tryCatch
185+
tryCatch,
186+
config
164187
}
165188

166189
const applyMiddlewares = async (

0 commit comments

Comments
 (0)