19988: Refactor getOrder into data explorer middleware when no order prefixes are...
[arvados-workbench2.git] / src / store / data-explorer / data-explorer-middleware-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch, MiddlewareAPI } from 'redux';
6 import { RootState } from '../store';
7 import { DataColumns } from 'components/data-table/data-table';
8 import { DataExplorer, getSortColumn } from './data-explorer-reducer';
9 import { ListResults } from 'services/common-service/common-service';
10 import { createTree } from 'models/tree';
11 import { DataTableFilters } from 'components/data-table-filters/data-table-filters-tree';
12 import { OrderBuilder, OrderDirection } from 'services/api/order-builder';
13 import { SortDirection } from 'components/data-table/data-column';
14 import { Resource } from 'models/resource';
15
16 export abstract class DataExplorerMiddlewareService {
17     protected readonly id: string;
18
19     protected constructor(id: string) {
20         this.id = id;
21     }
22
23     public getId() {
24         return this.id;
25     }
26
27     public getColumnFilters<T>(
28         columns: DataColumns<T, any>,
29         columnName: string
30     ): DataTableFilters {
31         return getDataExplorerColumnFilters(columns, columnName);
32     }
33
34     abstract requestItems(
35         api: MiddlewareAPI<Dispatch, RootState>,
36         criteriaChanged?: boolean
37     ): Promise<void>;
38 }
39
40 export const getDataExplorerColumnFilters = <T>(
41     columns: DataColumns<T, any>,
42     columnName: string
43 ): DataTableFilters => {
44     const column = columns.find((c) => c.name === columnName);
45     return column ? column.filters : createTree();
46 };
47
48 export const dataExplorerToListParams = (dataExplorer: DataExplorer) => ({
49     limit: dataExplorer.rowsPerPage,
50     offset: dataExplorer.page * dataExplorer.rowsPerPage,
51 });
52
53 export const getOrder = <T extends Resource = Resource>(dataExplorer: DataExplorer) => {
54     const sortColumn = getSortColumn<T>(dataExplorer);
55     const order = new OrderBuilder<T>();
56     if (sortColumn && sortColumn.sort) {
57         const sortDirection = sortColumn.sort.direction === SortDirection.ASC
58             ? OrderDirection.ASC
59             : OrderDirection.DESC;
60
61         return order
62             .addOrder(sortDirection, sortColumn.sort.field)
63             .getOrder();
64     } else {
65         return order.getOrder();
66     }
67 };
68
69 export const listResultsToDataExplorerItemsMeta = <R>({
70     itemsAvailable,
71     offset,
72     limit,
73 }: ListResults<R>) => ({
74     itemsAvailable,
75     page: Math.floor(offset / limit),
76     rowsPerPage: limit,
77 });