This repository has been archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
68 lines (60 loc) · 1.41 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
export const isPromise = payload => {
return Promise.resolve(payload) === payload;
};
export const isValid = action => {
return typeof action === 'object' &&
action.hasOwnProperty('type') &&
isPromise(action.payload)
}
export const PENDING = 'PENDING';
export const FULFILLED = 'FULFILLED';
export const REJECTED = 'REJECTED';
export const createAction = (type, promiseFn) => {
if (typeof promiseFn !== 'function') {
throw `The second argument to createAction must be a function. Received '${typeof promiseFn}'`
}
const pendingType = `${type}_${PENDING}`;
const fulfilledType = `${type}_${FULFILLED}`;
const rejectedType = `${type}_${REJECTED}`;
return [
(...args) => ({
type,
payload: promiseFn(...args),
pendingType,
fulfilledType,
rejectedType
}),
type,
pendingType,
fulfilledType,
rejectedType
]
};
export const promiseMiddleware = ({ dispatch }) => next => action => {
if (!isValid(action)) {
return next(action);
}
const {
type,
pendingType = PENDING,
fulfilledType = FULFILLED,
rejectedType = REJECTED,
payload,
...rest
} = action;
dispatch({ type: pendingType });
payload.then(payload => {
dispatch({
type,
payload,
...rest
});
dispatch({ type: fulfilledType });
})
.catch(err => {
dispatch({
type: rejectedType,
payload: err
});
});
};