1 |
|
2 | import { get, union, setWith, clone, mergeWith, isArray } from "lodash";
|
3 |
|
4 | import { isApi, isRequest, isFailure, isSuccess, isClear } from "./actions";
|
5 | import { Apis } from "./apis";
|
6 |
|
7 | export const initState = {
|
8 | loading: false,
|
9 | result: null,
|
10 | request: {},
|
11 | meta: {},
|
12 | total: 0,
|
13 | };
|
14 |
|
15 | function r(state = initState, action = {}) {
|
16 | const { payload = {}, error, meta = {} } = action;
|
17 | const { xTotalCount, result } = payload;
|
18 | const { append = false } = meta;
|
19 |
|
20 | if (isRequest(action)) {
|
21 | return { ...state, loading: true, request: payload, meta };
|
22 | }
|
23 |
|
24 | if (isSuccess(action)) {
|
25 | return {
|
26 | ...state,
|
27 | loading: false,
|
28 | result: append ? union(result, state.result) : result,
|
29 | total: xTotalCount && Number(xTotalCount),
|
30 | meta: { ...state.meta, ...meta },
|
31 | };
|
32 | }
|
33 |
|
34 | if (isFailure(action)) {
|
35 | return {
|
36 | ...state,
|
37 | loading: false,
|
38 | error,
|
39 | meta: { ...state.meta, ...meta },
|
40 | };
|
41 | }
|
42 |
|
43 | if (isClear(action)) {
|
44 | return initState;
|
45 | }
|
46 |
|
47 | return state;
|
48 | }
|
49 |
|
50 | const customizer = (objValue, srcValue, key, object, source, stack) => {
|
51 | if (stack.size === 2) {
|
52 |
|
53 | if (isArray(srcValue)) {
|
54 | return srcValue;
|
55 | }
|
56 | }
|
57 | };
|
58 |
|
59 | export function entitiesReducer(state = {}, action) {
|
60 | if (action.payload && action.payload.entities) {
|
61 | return mergeWith(state, action.payload.entities, customizer);
|
62 | }
|
63 | return state;
|
64 | }
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | export function apiReducer(state = {}, action) {
|
72 | const { key } = action;
|
73 |
|
74 | if (isApi(action)) {
|
75 |
|
76 | const api = Apis.get(key);
|
77 |
|
78 | if (!api) {
|
79 | return state;
|
80 | }
|
81 |
|
82 | return setWith(
|
83 | { ...state },
|
84 | api.reduxPath,
|
85 | r(get(state, api.reduxPath), action),
|
86 | clone
|
87 | );
|
88 | }
|
89 | return state;
|
90 | }
|
91 |
|
92 | const apiReducers = {
|
93 | apis: apiReducer,
|
94 | entities: entitiesReducer,
|
95 | };
|
96 |
|
97 | export default apiReducers;
|