Skip to content

Commit

Permalink
migrate rest of useApi to react-query
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Aug 22, 2023
1 parent 4685a65 commit 9272144
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 156 deletions.
1 change: 1 addition & 0 deletions x-pack/plugins/transform/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const TRANSFORM_REACT_QUERY_KEYS = {
GET_DATA_VIEW_TITLES: 'transform.get_data_view_titles',
GET_ES_INDICES: 'transform.get_es_indices',
GET_ES_INGEST_PIPELINES: 'transform.get_es_ingest_pipelines',
GET_HISTOGRAMS_FOR_FIELDS: 'transform.get_histograms_for_fields',
GET_PRIVILEGES: 'transform.get_privileges',
GET_TRANSFORM: 'transform.get_transform',
GET_TRANSFORM_AUDIT_MESSAGES: 'transform.get_transform_audit_messages',
Expand Down
35 changes: 0 additions & 35 deletions x-pack/plugins/transform/public/app/hooks/__mocks__/use_api.ts

This file was deleted.

1 change: 0 additions & 1 deletion x-pack/plugins/transform/public/app/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

export { useApi } from './use_api';
export { useCreateTransform } from './use_create_transform';
export { useDocumentationLinks } from './use_documentation_links';
export { useGetDataViewTitles } from './use_get_data_view_titles';
Expand Down
59 changes: 0 additions & 59 deletions x-pack/plugins/transform/public/app/hooks/use_api.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useQuery } from '@tanstack/react-query';

import type { IHttpFetchError } from '@kbn/core-http-browser';
import { KBN_FIELD_TYPES } from '@kbn/field-types';
import { DEFAULT_SAMPLER_SHARD_SIZE } from '@kbn/ml-agg-utils';

import { addInternalBasePath, TRANSFORM_REACT_QUERY_KEYS } from '../../../common/constants';
import type {
FieldHistogramsRequestSchema,
FieldHistogramsResponseSchema,
} from '../../../common/api_schemas/field_histograms';

import { useAppDependencies } from '../app_dependencies';

import type { SavedSearchQuery } from './use_search_items';

export interface FieldHistogramRequestConfig {
fieldName: string;
type?: KBN_FIELD_TYPES;
}

export const useGetHistogramsForFields = (
dataViewTitle: string,
fields: FieldHistogramRequestConfig[],
query: string | SavedSearchQuery,
runtimeMappings?: FieldHistogramsRequestSchema['runtimeMappings'],
enabled?: boolean,
samplerShardSize = DEFAULT_SAMPLER_SHARD_SIZE
) => {
const { http } = useAppDependencies();

return useQuery<FieldHistogramsResponseSchema, IHttpFetchError>(
[
TRANSFORM_REACT_QUERY_KEYS.GET_HISTOGRAMS_FOR_FIELDS,
{
dataViewTitle,
fields,
query,
runtimeMappings,
samplerShardSize,
},
],
({ signal }) =>
http.post<FieldHistogramsResponseSchema>(
addInternalBasePath(`field_histograms/${dataViewTitle}`),
{
body: JSON.stringify({
query,
fields,
samplerShardSize,
...(runtimeMappings !== undefined ? { runtimeMappings } : {}),
}),
version: '1',
signal,
}
),
{ enabled }
);
};
39 changes: 23 additions & 16 deletions x-pack/plugins/transform/public/app/hooks/use_index_data.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
*/

import React, { FC } from 'react';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import '@testing-library/jest-dom/extend-expect';
import { render, screen, waitFor } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';

import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import { CoreSetup } from '@kbn/core/public';
import { DataGrid, type UseIndexDataReturnType } from '@kbn/ml-data-grid';
import type { RuntimeMappings } from '@kbn/ml-runtime-field-utils';
Expand All @@ -25,7 +25,6 @@ import { useIndexData } from './use_index_data';

jest.mock('../../shared_imports');
jest.mock('../app_dependencies');
jest.mock('./use_api');

import { MlSharedContext } from '../__mocks__/shared_context';

Expand All @@ -45,13 +44,17 @@ const runtimeMappings: RuntimeMappings = {
},
};

const queryClient = new QueryClient();

describe('Transform: useIndexData()', () => {
test('dataView set triggers loading', async () => {
const mlShared = await getMlSharedImports();
const wrapper: FC = ({ children }) => (
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlShared}>{children}</MlSharedContext.Provider>
</IntlProvider>
<QueryClientProvider client={queryClient}>
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlShared}>{children}</MlSharedContext.Provider>
</IntlProvider>
</QueryClientProvider>
);

const { result, waitForNextUpdate } = renderHook(
Expand Down Expand Up @@ -102,11 +105,13 @@ describe('Transform: <DataGrid /> with useIndexData()', () => {
};

render(
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlSharedImports}>
<Wrapper />
</MlSharedContext.Provider>
</IntlProvider>
<QueryClientProvider client={queryClient}>
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlSharedImports}>
<Wrapper />
</MlSharedContext.Provider>
</IntlProvider>
</QueryClientProvider>
);

// Act
Expand Down Expand Up @@ -142,11 +147,13 @@ describe('Transform: <DataGrid /> with useIndexData()', () => {
};

render(
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlSharedImports}>
<Wrapper />
</MlSharedContext.Provider>
</IntlProvider>
<QueryClientProvider client={queryClient}>
<IntlProvider locale="en">
<MlSharedContext.Provider value={mlSharedImports}>
<Wrapper />
</MlSharedContext.Provider>
</IntlProvider>
</QueryClientProvider>
);

// Act
Expand Down
82 changes: 37 additions & 45 deletions x-pack/plugins/transform/public/app/hooks/use_index_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ import {
} from '@kbn/ml-data-grid';
import type { TimeRange as TimeRangeMs } from '@kbn/ml-date-picker';

import {
isEsSearchResponse,
isFieldHistogramsResponseSchema,
} from '../../../common/api_schemas/type_guards';
import { isEsSearchResponse } from '../../../common/api_schemas/type_guards';
import {
hasKeywordDuplicate,
isKeywordDuplicate,
Expand All @@ -44,7 +41,7 @@ import { useToastNotifications, useAppDependencies } from '../app_dependencies';
import type { StepDefineExposedState } from '../sections/create_transform/components/step_define/common';

import { SearchItems } from './use_search_items';
import { useApi } from './use_api';
import { useGetHistogramsForFields } from './use_get_histograms_for_fields';
import { useDataSearch } from './use_data_search';

export const useIndexData = (
Expand All @@ -61,7 +58,6 @@ export const useIndexData = (

const indexPattern = useMemo(() => dataView.getIndexPattern(), [dataView]);

const api = useApi();
const dataSearch = useDataSearch();
const toastNotifications = useToastNotifications();

Expand Down Expand Up @@ -273,58 +269,54 @@ export const useIndexData = (
]),
]);

useEffect(() => {
const fetchColumnChartsData = async function () {
const allDataViewFieldNames = new Set(dataView.fields.map((f) => f.name));
const columnChartsData = await api.getHistogramsForFields(
indexPattern,
columns
.filter((cT) => dataGrid.visibleColumns.includes(cT.id))
.map((cT) => {
// If a column field name has a corresponding keyword field,
// fetch the keyword field instead to be able to do aggregations.
const fieldName = cT.id;
return hasKeywordDuplicate(fieldName, allDataViewFieldNames)
? {
fieldName: `${fieldName}.keyword`,
type: getFieldType(undefined),
}
: {
fieldName,
type: getFieldType(cT.schema),
};
}),
isDefaultQuery(query) ? defaultQuery : queryWithBaseFilterCriteria,
combinedRuntimeMappings
);
const allDataViewFieldNames = new Set(dataView.fields.map((f) => f.name));
const { error: histogramsForFieldsError, data: histogramsForFieldsData } =
useGetHistogramsForFields(
indexPattern,
columns
.filter((cT) => dataGrid.visibleColumns.includes(cT.id))
.map((cT) => {
// If a column field name has a corresponding keyword field,
// fetch the keyword field instead to be able to do aggregations.
const fieldName = cT.id;
return hasKeywordDuplicate(fieldName, allDataViewFieldNames)
? {
fieldName: `${fieldName}.keyword`,
type: getFieldType(undefined),
}
: {
fieldName,
type: getFieldType(cT.schema),
};
}),
isDefaultQuery(query) ? defaultQuery : queryWithBaseFilterCriteria,
combinedRuntimeMappings,
chartsVisible
);

if (!isFieldHistogramsResponseSchema(columnChartsData)) {
showDataGridColumnChartErrorMessageToast(columnChartsData, toastNotifications);
return;
}
useEffect(() => {
if (histogramsForFieldsError !== null) {
showDataGridColumnChartErrorMessageToast(histogramsForFieldsError, toastNotifications);
}
// custom comparison
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [histogramsForFieldsError]);

useEffect(() => {
if (histogramsForFieldsData) {
setColumnCharts(
// revert field names with `.keyword` used to do aggregations to their original column name
columnChartsData.map((d) => ({
histogramsForFieldsData.map((d) => ({
...d,
...(isKeywordDuplicate(d.id, allDataViewFieldNames)
? { id: removeKeywordPostfix(d.id) }
: {}),
}))
);
};

if (chartsVisible) {
fetchColumnChartsData();
}
// custom comparison
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
chartsVisible,
indexPattern,
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify([query, dataGrid.visibleColumns, combinedRuntimeMappings, timeRangeMs]),
]);
}, [histogramsForFieldsData]);

const renderCellValue = useRenderCellValue(dataView, pagination, tableItems);

Expand Down

0 comments on commit 9272144

Please sign in to comment.