UNPKG

2.02 kBJavaScriptView Raw
1/// <reference path='../typings/index.d.ts' />
2import { get, union, setWith, clone, mergeWith, isArray } from "lodash";
3
4import { isApi, isRequest, isFailure, isSuccess, isClear } from "./actions";
5import { Apis } from "./apis";
6
7export const initState = {
8 loading: false,
9 result: null,
10 request: {},
11 meta: {},
12 total: 0,
13};
14
15function 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
50const customizer = (objValue, srcValue, key, object, source, stack) => {
51 if (stack.size === 2) {
52 // will not merge array
53 if (isArray(srcValue)) {
54 return srcValue;
55 }
56 }
57};
58
59export 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 * api root reducer
68 * @param {Object} state state
69 * @param {import("@36node/redux-api").Action} action action
70 */
71export function apiReducer(state = {}, action) {
72 const { key } = action;
73
74 if (isApi(action)) {
75 // key not register
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
92const apiReducers = {
93 apis: apiReducer,
94 entities: entitiesReducer,
95};
96
97export default apiReducers;