-
Notifications
You must be signed in to change notification settings - Fork 1
/
redux-middleware.js
123 lines (103 loc) · 2.57 KB
/
redux-middleware.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'use strict';
Redux.middle = {}
Redux.middle.thunkMiddleware = function(_ref) {
var dispatch = _ref.dispatch;
var getState = _ref.getState;
return function(next) {
return function(action) {
if (typeof action === 'function') {
return action(dispatch, getState);
}
return next(action);
};
};
}
Redux.middle.logger = function(store) {
return function(next) {
return function(action) {
console.log('dispatching', action);
var result = next(action);
console.log('next state', store.getState());
return result;
};
};
};
Redux.middle.crashReporter = function(store) {
return function(next) {
return function(action) {
try {
return next(action);
} catch (err) {
console.error('Caught an exception!', err);
Raven.captureException(err, {
extra: {
action: action,
state: store.getState()
}
});
throw err;
}
};
};
};
Redux.middle.timeoutScheduler = function(store) {
return function(next) {
return function(action) {
if (!action.meta || !action.meta.delay) {
return next(action);
}
var timeoutId = setTimeout(function() {
return next(action);
}, action.meta.delay);
return function cancel() {
clearTimeout(timeoutId);
};
};
};
};
Redux.middle.vanillaPromise = function(store) {
return function(next) {
return function(action) {
if (typeof action.then !== 'function') {
return next(action);
}
return Promise.resolve(action).then(store.dispatch);
};
};
};
Redux.middle.readyStatePromise = function(store) {
return function(next) {
return function(action) {
if (!action.promise) {
return next(action);
}
function makeAction(ready, data) {
var newAction = Object.assign({}, action, {
ready: ready
}, data);
delete newAction.promise;
return newAction;
}
var SUCCESS = FAILURE = REQUEST = action.type;
if (action.types && Array.isArray(action.types)) {
REQUEST = action.types[0];
SUCCESS = action.types[1];
FAILURE = action.types[2];
}
next(makeAction(false, {
type: REQUEST
}));
return action.promise.then(function(result) {
return next(makeAction(true, {
result: result,
type: SUCCESS
}));
}, function(error) {
return next(makeAction(true, {
error: error,
type: FAILURE
}));
});
};
};
};