This repository has been archived by the owner on Jul 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
77 lines (68 loc) · 1.74 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const REDUX_LISTEN_RESOLVE = 'REDUX_LISTEN_RESOLVE'
module.exports = function createReduxListen() {
let listeners = []
let pendingCount = 0
function getListeners() {
return listeners
}
function isPending() {
return pendingCount > 0
}
function addListener(type, fn) {
listeners.push({ fn, type, isRegExp: type instanceof RegExp })
return fn
}
function addListeners(obj) {
Object.keys(obj).map(type => addListener(type, obj[type]))
return obj
}
function removeListeners({ type, fn } = {}) {
listeners = listeners.filter(
_ => (type && _.type !== type) || (fn && _.fn !== fn)
)
return listeners
}
function decrementPendingCount(dispatch) {
let called = false
return () => {
if (called) return pendingCount
called = true
pendingCount -= 1
if (pendingCount <= 0) {
pendingCount = 0
dispatch({ type: REDUX_LISTEN_RESOLVE })
}
return pendingCount
}
}
const middleware = store => next => action => {
const result = next(action)
try {
const { getState, dispatch } = store
const matches = listeners.filter(
({ type, isRegExp }) =>
type === '*' ||
(isRegExp ? action.type.match(type) : type === action.type)
)
pendingCount += matches.filter(({ fn }) => fn.length > 1).length
matches.map(({ fn }) =>
fn(
{ getState, action, dispatch },
fn.length > 1 && decrementPendingCount(dispatch)
)
)
} catch (e) {
console.error(e) // eslint-disable-line no-console
}
return result
}
return {
getListeners,
isPending,
addListener,
addListeners,
removeListeners,
decrementPendingCount,
middleware,
}
}