-
-
Notifications
You must be signed in to change notification settings - Fork 419
/
index.ts
99 lines (91 loc) · 2.95 KB
/
index.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
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
import { Action, Model, PluginCreator } from '@rematch/core'
const createLoadingAction = (show) => (state, { name, action }: any) => ({
...state,
effects: {
...state.effects,
[name]: {
...state.effects[name],
[action]: show,
},
},
global: show,
models: { ...state.models, [name]: show },
})
interface LoadingConfig {
name?: string,
whitelist?: string[],
blacklist?: string[],
}
const loadingPlugin = (config: LoadingConfig = {}): any => {
// validate config
if (config.name && typeof config.name !== 'string') {
throw new Error('loading plugin config name must be a string')
}
if (config.whitelist && !Array.isArray(config.whitelist)) {
throw new Error('loading plugin config whitelist must be an array of strings')
}
if (config.blacklist && !Array.isArray(config.blacklist)) {
throw new Error('loading plugin config blacklist must be an array of strings')
}
if (config.whitelist && config.blacklist) {
throw new Error('loading plugin config cannot have both a whitelist & a blacklist')
}
const loadingModelName = config.name || 'loading'
const loading: Model = {
name: loadingModelName,
reducers: {
hide: createLoadingAction(false),
show: createLoadingAction(true),
},
state: {
effects: {},
global: false,
models: {},
},
}
return {
config: {
models: {
loading,
},
},
init: ({ dispatch }) => ({
onModel({ name }: Model) {
// do not run dispatch on loading model
if (name === loadingModelName) { return }
loading.state.models[name] = false
loading.state.effects[name] = {}
const modelActions = dispatch[name]
// map over effects within models
Object.keys(modelActions).forEach((action: string) => {
if (dispatch[name][action].isEffect) {
// ignore items not in whitelist
if (config.whitelist && !config.whitelist.includes(`${name}/${action}`)) {
return
}
// ignore items in blacklist
if (config.blacklist && config.blacklist.includes(`${name}/${action}`)) {
return
}
// copy function
loading.state.effects[name][action] = false
const fn = dispatch[name][action]
// create function with pre & post loading calls
const dispatchWithHooks = (props) => {
dispatch.loading.show({ name, action })
return fn(props)
.catch(() => dispatch.loading.hide({ name, action }))
.then(() => dispatch.loading.hide({ name, action }))
// waits for dispatch function to finish before calling "hide"
}
// replace existing effect with new dispatch
dispatch[name][action] = dispatchWithHooks
} else {
loading.state.models[name] = false
}
})
},
}),
}
}
export default loadingPlugin