UNPKG

2.94 kBJavaScriptView Raw
1// @flow
2/* eslint-disable max-lines-per-function, */
3
4import type { PaginatorSettings } from "./types";
5
6type EndpointData = {
7 path : string;
8 cb : () => string;
9};
10
11
12/*
13if (typeof Endpoint === "object") {
14 return {
15 path : Endpoint.path,
16 cb : Endpoint.cb,
17 };
18}
19
20return {
21 path : Endpoint,
22};
23*/
24type Endpoint = EndpointData | string;
25
26type CreatePaginator = (endpoint: Endpoint, info: PaginatorSettings) => any;
27
28type OnlyForEndpoint = (endpoint : string, reducer : any) =>
29(state? : any, action : { meta: { endpoint : string }}) => any;
30
31import {
32 pages as pagesReducer,
33 items as itemsReducer,
34 dataItems as dataItemsReducer,
35} from "./reducers";
36
37import actions from "./actions";
38
39import * as Immutable from "immutable";
40
41import { rowsPerLoad as defaultRowsPerLoad } from "x25/utility/others";
42
43export const onlyForEndpoint : OnlyForEndpoint = (endpoint, reducer) => (
44 (state = Immutable.Map(), action) => {
45 if (typeof action.meta === "undefined" || action.meta.endpoint !== endpoint) {
46 return state;
47 }
48
49 return reducer(state, action);
50 }
51);
52
53const getEndpoint = (data : Endpoint) => {
54 if (typeof data === "object") {
55 return {
56 path : data.path,
57 cb : data.cb,
58 };
59 }
60
61 return {
62 path : data,
63 cb : null,
64 };
65};
66
67export const createPaginator : CreatePaginator = (
68 (endpointData : Endpoint, settings : PaginatorSettings) => {
69 const {
70 path: endpoint,
71 cb: endpointCb,
72 } = getEndpoint(endpointData);
73
74 const {
75 key,
76 normalizeDataItem,
77 dataItemURL,
78 manageEntity,
79 resultsKey,
80 totalKey = "Total",
81 pageArgName = "page",
82 idKey = "ID",
83 rowsPerLoad = defaultRowsPerLoad,
84 manipulateItems = (items) => items,
85 } = settings;
86
87 const endpointedActions = ({
88 requestPage: (page : number, token : string) => actions.requestPage({
89 endpoint,
90 endpointCb,
91 manageEntity,
92 resultsKey,
93 totalKey,
94 pageArgName,
95 idKey,
96 page,
97 token,
98 }),
99 resetView (token) {
100 return actions.resetView(endpoint, token);
101 },
102 changeView ({ view, token } : { view : number; token : string; }) {
103 return actions.changeView(endpoint, {
104 view,
105 token,
106 });
107 },
108 clearData () {
109 return actions.clearData(endpoint);
110 },
111 });
112
113 return ({
114 key,
115 normalizeDataItem,
116 dataItemURL,
117 manipulateItems,
118 rowsPerLoad,
119 manageEntity,
120 resultsKey,
121 endpoint,
122
123 pagesReducer : onlyForEndpoint(endpoint, pagesReducer),
124 itemsReducer : onlyForEndpoint(endpoint, itemsReducer),
125
126 dataItemsReducer: onlyForEndpoint(endpoint, dataItemsReducer),
127
128 ...endpointedActions,
129 });
130 }
131);