-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
45 lines (36 loc) · 1.52 KB
/
middleware.js
File metadata and controls
45 lines (36 loc) · 1.52 KB
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
import _isPlainObject from 'lodash-es/isPlainObject';
const defaultErrorHandler = (error) => {
throw error;
};
const prepare = (action, dispatch, getState, errorHandler = defaultErrorHandler) => {
// Multiple dispatch (redux-multi)
if (Array.isArray(action)) {
return action.filter(v => v).map(p => prepare(p, dispatch, getState));
}
// Function wraper (redux-thunk)
if (typeof action === 'function') {
return action(p => prepare(p, dispatch, getState, errorHandler), getState);
}
// Promise, detect errors on rejects
// Detect action through instanceof Promise is not working in production mode, then used single detection by type
if (typeof action === 'object' && typeof action.then === 'function' && typeof action.catch === 'function') {
return action
.then(payload => prepare(payload, dispatch, getState, errorHandler))
.catch(e => {
errorHandler(e, p => prepare(p, dispatch, getState, errorHandler));
});
}
// Default case
if (_isPlainObject(action) && action.type) {
if (process.env.NODE_ENV !== 'production') {
window.__snapshot = (window.__snapshot || []).concat({action});
}
try {
return dispatch(action);
} catch (e) {
errorHandler(e, p => prepare(p, dispatch, getState, errorHandler));
}
}
return action;
};
export default (errorHandler) => ({getState}) => next => action => prepare(action, next, getState, errorHandler);