-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (59 loc) · 2.06 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
if (typeof console === "undefined") {
console = {};
}
if (typeof console.error !== "function") {
console.error = (error) => (error);
}
const isPromise = (p) => (p && typeof p.then === "function");
const tryCall = (fn, ...args) => {
if (typeof fn === "function") {
try {
return fn(...args);
} catch (exception) {
console.error("[TRY_CALL]", exception);
}
}
return null;
};
const INIT_ERROR = () => {
throw new Error(`Compose monitor into Redux store first. e.g.
const monitor = createMonitor();
const store = createStore(reducers, compose(monitor, applyMiddleware(...middlewares)));
monitor.dispatch(...actions).done(fullFill);`);
}
const monitorPromise = (getState, tasks = []) => {
const p = tasks.length === 0 ?
Promise.resolve() :
Promise.all(tasks).then(() => Promise.resolve());
p.done = (fullFill) => p.then(() => tryCall(fullFill, getState()));
return p;
};
export const createMonitor = () => {
const monitor = (createStore) => (reducer, preloadedState, enhancer) => {
const store = createStore(reducer, preloadedState, enhancer);
const { dispatch, getState } = store;
monitor.dispatch = (...actions) => {
const tasks = actions.reduce((res, action) => {
try {
const result = dispatch(action);
if (isPromise(result)) {
res.push(result.catch((error) => {
console.error("[DISPATCH_ACTION]", error);
return Promise.resolve();
}));
} else {
res.push(Promise.resolve(result));
}
} catch (exception) {
console.error("[DISPATCH_EXCEPTION]", exception)
}
return res;
}, []);
return monitorPromise(getState, tasks);
};
return store;
};
monitor.dispatch = INIT_ERROR;
return monitor;
};
export default createMonitor();