1 |
|
2 |
|
3 |
|
4 | import type { Dispatch, Action } from "./types";
|
5 |
|
6 | import { REQUEST_PAGE } from "./actionTypes";
|
7 | import actions from "./actions";
|
8 | import { fetchPage } from "./agent";
|
9 |
|
10 | const { receivePage } = actions;
|
11 |
|
12 | const paginatorMiddleware = ({ dispatch } : { dispatch : Dispatch}) => (
|
13 | (next : any) => (action : Action) => {
|
14 | if (action.type === REQUEST_PAGE) {
|
15 | const {
|
16 | meta: {
|
17 | endpoint,
|
18 | endpointCb,
|
19 | manageEntity,
|
20 | resultsKey,
|
21 | totalKey,
|
22 | pageArgName,
|
23 | idKey,
|
24 | },
|
25 | payload: {
|
26 | page,
|
27 | token,
|
28 | },
|
29 | } = action;
|
30 |
|
31 | dispatch((dispatch2) => {
|
32 | const markAsError = () => {
|
33 | dispatch2(receivePage({
|
34 | endpoint,
|
35 | endpointCb,
|
36 | manageEntity,
|
37 | pageArgName,
|
38 | idKey,
|
39 | page,
|
40 | error : true,
|
41 | token,
|
42 | items : [],
|
43 | total : 0,
|
44 | }));
|
45 | };
|
46 |
|
47 | const rawPath = typeof endpointCb === "function" ? endpointCb(token) : endpoint;
|
48 | const path = rawPath === null ? "" : rawPath;
|
49 |
|
50 | try {
|
51 | fetchPage({
|
52 | endpoint: path,
|
53 | pageArgName,
|
54 | page,
|
55 | token,
|
56 | }).
|
57 | then((res) => {
|
58 | const { response } = res;
|
59 | let
|
60 | results = [],
|
61 | total = 0;
|
62 |
|
63 | if (typeof resultsKey === "undefined") {
|
64 | results = response;
|
65 | } else {
|
66 | results = response[resultsKey];
|
67 | total = response[totalKey];
|
68 | }
|
69 | dispatch2(receivePage({
|
70 | endpoint,
|
71 | endpointCb,
|
72 | manageEntity,
|
73 | pageArgName,
|
74 | idKey,
|
75 | page,
|
76 | error : false,
|
77 | token,
|
78 | items : results,
|
79 | total,
|
80 | }));
|
81 | }).
|
82 | catch(() => {
|
83 | markAsError();
|
84 | });
|
85 | } catch (err) {
|
86 | markAsError();
|
87 | }
|
88 | });
|
89 | }
|
90 | return next(action);
|
91 | }
|
92 | );
|
93 |
|
94 | export default paginatorMiddleware;
|