UNPKG

2.78 kBJSXView Raw
1// @flow
2
3import type {
4 ItemsState,
5 PagesState,
6
7 Action,
8 ReceivePageAction,
9 ChangeViewAction,
10 RequestPageAction,
11} from "./types";
12
13import * as Immutable from "immutable";
14
15const
16 requestPage = (state : PagesState, action : RequestPageAction) => {
17 const { payload : { token, page } } = action;
18
19 const elements = Immutable.Map({
20 page,
21 error : false,
22 fetching : true,
23 fetched : false,
24 });
25
26 if (state.has(token)) {
27 return state.update(token, (current) => (
28 current.merge(elements)
29 ));
30 }
31
32 const init = elements.merge({
33 view : 1,
34 token,
35 ids : Immutable.List(),
36 });
37
38 return state.set(token, init);
39 },
40 receivePage = (state : PagesState, action : ReceivePageAction) => {
41 const {
42 meta: { idKey },
43 payload : { token, items, total, error },
44 } = action;
45
46 if (state.has(token)) {
47 const hasError = error === true;
48
49 return state.update(token, (current) => (
50 current.update((page) => (
51 current.merge(
52 Immutable.Map({
53 ids: page.get("ids").concat(
54 Immutable.List(
55 items.map((item) => String(item[idKey]))
56 )
57 ),
58 fetching : false,
59 error : hasError,
60 fetched : true,
61 total : hasError ? page.get("total") : total,
62 })
63 )
64 ))
65 ));
66 }
67
68 return state;
69 },
70 performChangeView = (state : PagesState, action : any, view : number) => {
71 const { payload : { token } } = action;
72
73 const item = state.get(token);
74
75 if (typeof item === "undefined") {
76 return state;
77 }
78
79 return state.update(token, (current) => (
80 current.set("view", view)
81 ));
82 },
83 changeView = (state : PagesState, action : ChangeViewAction) => (
84 performChangeView(state, action, action.payload.view)
85 ),
86 resetView = (state : PagesState, action : Action) => (
87 performChangeView(state, action, 1)
88 ),
89 receivePageItems = (state : ItemsState, action : ReceivePageAction) => {
90 const { payload, meta } = action;
91 const { items : payloadItems } = payload;
92 const { idKey, manageEntity } = meta;
93
94 const manage : any = (
95 typeof manageEntity === "function"
96 ) ? manageEntity : (item) => Immutable.Map(item);
97
98 const newItems = payloadItems.reduce((previous, item) => (
99 previous.set(String(item[idKey]), manage(item, state, idKey))
100 ), Immutable.Map());
101
102 return state.merge(newItems);
103 };
104
105export {
106 requestPage,
107 receivePage,
108 performChangeView,
109 changeView,
110 resetView,
111 receivePageItems,
112};