9be59811fff0e3055e2df95f468647d2e2957c06
[arvados-workbench2.git] / src / views / project-panel / project-panel-middleware.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Middleware } from "redux";
6 import actions from "../../store/data-explorer/data-explorer-action";
7 import { PROJECT_PANEL_ID, columns } from "./project-panel";
8 import { groupsService } from "../../services/services";
9 import { RootState } from "../../store/store";
10 import { getDataExplorer } from "../../store/data-explorer/data-explorer-reducer";
11 import { resourceToDataItem } from "./project-panel-item";
12
13 export const projectPanelMiddleware: Middleware = store => next => {
14     next(actions.SET_COLUMNS({ id: PROJECT_PANEL_ID, columns }));
15
16     return action => {
17
18         const handleProjectPanelAction = <T extends { id: string }>(handler: (data: T) => void) =>
19             (data: T) => {
20                 next(action);
21                 if (data.id === PROJECT_PANEL_ID) {
22                     handler(data);
23                 }
24             };
25
26         actions.match(action, {
27             SET_PAGE: handleProjectPanelAction(() => {
28                 store.dispatch(actions.REQUEST_ITEMS({ id: PROJECT_PANEL_ID }));
29             }),
30             SET_ROWS_PER_PAGE: handleProjectPanelAction(() => {
31                 store.dispatch(actions.REQUEST_ITEMS({ id: PROJECT_PANEL_ID }));
32             }),
33             REQUEST_ITEMS: handleProjectPanelAction(() => {
34                 const state = store.getState() as RootState;
35                 const dataExplorer = getDataExplorer(state.dataExplorer, PROJECT_PANEL_ID);
36                 groupsService
37                     .contents(state.projects.currentItemId, {
38                         limit: dataExplorer.rowsPerPage,
39                         offset: dataExplorer.page * dataExplorer.rowsPerPage,
40                     })
41                     .then(response => {
42                         store.dispatch(actions.SET_ITEMS({
43                             id: PROJECT_PANEL_ID,
44                             items: response.items.map(resourceToDataItem),
45                             itemsAvailable: response.itemsAvailable,
46                             page: Math.floor(response.offset / response.limit),
47                             rowsPerPage: response.limit
48                         }));
49                     });
50
51             }),
52             default: () => next(action)
53         });
54     };
55 };