Skip to content

Commit

Permalink
move repeating tanstack query options to a function
Browse files Browse the repository at this point in the history
  • Loading branch information
maximpn committed Nov 25, 2024
1 parent b302226 commit 0b52f0b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
* 2.0.
*/

import type { QueryClient, QueryFunction, QueryKey } from '@tanstack/react-query';
import type {
FetchQueryOptions,
QueryClient,
QueryFunction,
QueryKey,
} from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import type { DatatableColumn } from '@kbn/expressions-plugin/common';
import { getESQLQueryColumns } from '@kbn/esql-utils';
Expand All @@ -22,12 +27,7 @@ export async function fetchEsqlQueryColumns({
esqlQuery,
queryClient,
}: FetchEsqlQueryColumnsParams): Promise<DatatableColumn[]> {
const data = await queryClient.fetchQuery({
queryKey: [esqlQuery.trim()],
queryFn: queryEsqlColumnsFactory(esqlQuery),
staleTime: DEFAULT_STALE_TIME,
retry: false,
});
const data = await queryClient.fetchQuery(createSharedTanstackQueryOptions(esqlQuery));

if (data instanceof Error) {
throw data;
Expand All @@ -43,10 +43,7 @@ interface UseEsqlQueryColumnsResult {

export function useEsqlQueryColumns(esqlQuery: string): UseEsqlQueryColumnsResult {
const { data, isLoading } = useQuery({
queryKey: [esqlQuery.trim()],
queryFn: queryEsqlColumnsFactory(esqlQuery),
staleTime: DEFAULT_STALE_TIME,
retry: false,
...createSharedTanstackQueryOptions(esqlQuery),
retryOnMount: false,
refetchOnMount: false,
refetchOnWindowFocus: false,
Expand All @@ -55,6 +52,17 @@ export function useEsqlQueryColumns(esqlQuery: string): UseEsqlQueryColumnsResul
return { columns: !data || data instanceof Error ? [] : data, isLoading };
}

function createSharedTanstackQueryOptions(
esqlQuery: string
): FetchQueryOptions<DatatableColumn[] | Error> {
return {
queryKey: [esqlQuery.trim()],
queryFn: queryEsqlColumnsFactory(esqlQuery),
staleTime: DEFAULT_STALE_TIME,
retry: false,
};
}

function queryEsqlColumnsFactory(
esqlQuery: string
): QueryFunction<DatatableColumn[] | Error, QueryKey> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,8 @@ describe('StepDefineRule', () => {
});

it('updates EQL query correctly', async () => {
jest.useFakeTimers();

const timelineEqlQuery = {
index: ['.alerts-security.alerts-default', 'logs-*', 'packetbeat-*'],
queryBar: {
Expand Down Expand Up @@ -714,6 +716,8 @@ describe('StepDefineRule', () => {

await setRuleFromTimeline();

jest.runAllTimers();

expect(screen.getByTestId('eqlQueryBarTextInput')).toHaveValue(
timelineEqlQuery.queryBar.query.query
);
Expand Down

0 comments on commit 0b52f0b

Please sign in to comment.