Update SearchReactEmbeddable example to use sessionId and abortSignal (#181249)

Fixes https://github.com/elastic/kibana/issues/181199

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Nathan Reese 2024-04-23 08:07:33 -06:00 committed by GitHub
parent 0a4081e1d8
commit 46cb23a80d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 18 additions and 4 deletions

View file

@ -16,7 +16,9 @@ export async function getCount(
dataService: DataPublicPluginStart,
filters: Filter[],
query: Query | AggregateQuery | undefined,
timeRange: TimeRange | undefined
timeRange: TimeRange | undefined,
abortSignal: AbortSignal,
sessionId?: string
) {
const searchSource = await dataService.search.searchSource.create();
searchSource.setField('index', dataView);
@ -38,7 +40,9 @@ export async function getCount(
const { rawResponse: resp } = await lastValueFrom(
searchSource.fetch$({
abortSignal,
legacyHitsTotal: false,
sessionId,
})
);
// eslint-disable-next-line no-console

View file

@ -15,7 +15,7 @@ import {
useBatchedPublishingSubjects,
} from '@kbn/presentation-publishing';
import React, { useEffect } from 'react';
import { BehaviorSubject, switchMap } from 'rxjs';
import { BehaviorSubject, switchMap, tap } from 'rxjs';
import { SEARCH_EMBEDDABLE_ID } from './constants';
import { getCount } from './get_count';
import { Api, Services, State } from './types';
@ -55,8 +55,14 @@ export const getSearchEmbeddableFactory = (services: Services) => {
const error$ = new BehaviorSubject<Error | undefined>(undefined);
const count$ = new BehaviorSubject<number>(0);
let prevRequestAbortController: AbortController | undefined;
const fetchSubscription = fetch$(api)
.pipe(
tap(() => {
if (prevRequestAbortController) {
prevRequestAbortController.abort();
}
}),
switchMap(async (fetchContext) => {
error$.next(undefined);
if (!defaultDataView) {
@ -65,6 +71,8 @@ export const getSearchEmbeddableFactory = (services: Services) => {
try {
dataLoading$.next(true);
const abortController = new AbortController();
prevRequestAbortController = abortController;
const count = await getCount(
defaultDataView,
services.data,
@ -79,11 +87,13 @@ export const getSearchEmbeddableFactory = (services: Services) => {
to: new Date(fetchContext.timeslice[1]).toISOString(),
mode: 'absolute' as 'absolute',
}
: fetchContext.timeRange
: fetchContext.timeRange,
abortController.signal,
fetchContext.searchSessionId
);
return { count };
} catch (error) {
return { error };
return error.name === 'AbortError' ? undefined : { error };
}
})
)