This repository has been archived by the owner on Sep 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreducerCreator.ts
66 lines (63 loc) · 2.13 KB
/
reducerCreator.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
import {merge} from 'lodash'
export interface IReducer {
reducer: Function
}
const restrictedActionNames = {
TYPES: true,
reducer: true
}
export default function makeReducer
<ISubState, T, V>
(defaultState: ISubState, Actions?: T, AsyncActions?: V): (ID: string) => V & T & IReducer {
return (ID: string) => {
if (!ID || typeof ID === 'undefined') {
throw new Error('Reducers must have an ID')
}
if (typeof defaultState === 'undefined') {
throw new Error('Reducers must have a default state')
}
const newSyncActions: T & IReducer = merge(({} as IReducer), Actions)
const newAsyncActions: V = merge({}, AsyncActions)
const TYPES = {}
// Actions are now functions that auto return types
Object.keys(Actions).forEach((key) => {
if (restrictedActionNames[key]) {
throw new Error(`You cannot have an action called '${key}'`)
}
const type = `${ID}/${key}`
TYPES[key] = type
newSyncActions[key] = (...payload: any[]) => {
return { type, payload }
}
})
if (AsyncActions) {
// async actions have dispatch and the payload injected into them.
Object.keys(AsyncActions).forEach((key) => {
if (Actions[key]) {
throw new Error('You cannot have a Action and Async Action with the same name: ' + key)
}
newAsyncActions[key] = (...payload: any[]) => {
return (dispatch: Function, getState: Function) =>
AsyncActions[key](...payload, newSyncActions, dispatch, getState)
}
})
}
const baseReducer = {
TYPES,
reducer: (state: ISubState, action: {type: string, payload?: any}) => {
state = state || defaultState
/* tslint:disable */
// Linting is disabled because there is no other way to do this
const [ActionID, actionMethod] = action.type.split('/')
if (ActionID === ID) {
if (newSyncActions[actionMethod]) {
return Actions[actionMethod](...action.payload, state)
}
}
return state
/* tslint:enable */
}
}
return merge(baseReducer, newSyncActions, newAsyncActions)
}
}