-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreateActions.ts
62 lines (60 loc) · 1.54 KB
/
createActions.ts
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
const isPromise = (obj: any) => {
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function'
)
}
const createActions = (actions: any, dispatch: any, additions?: string[]) => {
const haveLoading = additions && additions.find(i => i === 'loading')
const res: any = {}
Object.keys(actions).forEach((key) => {
res[key] = (...args: any) => {
const val = actions[key](...args)
if (isPromise(val)) {
return new Promise((resolve) => {
if (haveLoading) {
dispatch({
type: '@@loading/start',
payload: key
})
}
val.then((v: any) => {
dispatch({
payload: v,
type: key
})
if (haveLoading) {
dispatch({
type: '@@loading/end',
payload: key
})
}
resolve({ payload: v, type: key })
}).catch((err: any) => {
dispatch({
payload: err,
type: key,
error: true
})
if (haveLoading) {
dispatch({
type: '@@loading/end',
payload: key
})
}
resolve({ payload: err, type: key, error: true })
})
})
} else {
dispatch({
payload: val,
type: key
})
return { payload: val, type: key }
}
}
})
return res
}
export default createActions