import { ElasticsearchClient } from 'kibana/server' ; import type { Filter , FoundListItemSchema , ListId , Page , PerPage , SortFieldOrUndefined , SortOrderOrUndefined , } from '@kbn/securitysolution-io-ts-list-types' ; import { SearchEsListItemSchema } from '../../schemas/elastic_response' ; import { getList } from '../lists' ; import { encodeCursor , getQueryFilterWithListId , getSearchAfterWithTieBreaker , getSortWithTieBreaker , scrollToStartPage , transformElasticToListItem , } from '../utils' ; export interface FindListItemOptions { listId : ListId ; filter : Filter ; currentIndexPosition : number ; searchAfter : string [ ] | undefined ; perPage : PerPage ; page : Page ; sortField : SortFieldOrUndefined ; sortOrder : SortOrderOrUndefined ; esClient : ElasticsearchClient ; listIndex : string ; listItemIndex : string ; } export const findListItem = async ( { esClient , currentIndexPosition , filter , listId , page , perPage , searchAfter , sortField : sortFieldWithPossibleValue , listIndex , listItemIndex , sortOrder , } ) : Promise < FoundListItemSchema | null > => { const list = await getList ( { esClient , id : listId , listIndex } ) ; if ( list == null ) { return null ; } else { const query = getQueryFilterWithListId ( { filter , listId } ) ; const sortField = sortFieldWithPossibleValue === 'value' ? list . type : sortFieldWithPossibleValue ; const scroll = await scrollToStartPage ( { currentIndexPosition , esClient , filter , hopSize : 100 , index : listItemIndex , page , perPage , searchAfter , sortField , sortOrder , } ) ; const { body : respose } = await esClient . count ( { body : { query , } , ignore_unavailable : true , index : listItemIndex , } ) ; if ( scroll . validSearchAfterFound ) { const { body : response } = await esClient . search < SearchEsListItemSchema > ( { body : { query , search_after : scroll . searchAfter , sort : getSortWithTieBreaker ( { sortField , sortOrder } ) , } , ignore_unavailable : true , index : listItemIndex , seq_no_primary_term : true , size : perPage , } ) ; return { cursor : encodeCursor ( { page , perPage , searchAfter : getSearchAfterWithTieBreaker ( { response , sortField } ) , } ) , data : transformElasticToListItem ( { response , type : list . type } ) , page , per_page : perPage , total : respose . count , } ; } else { return { cursor : encodeCursor ( { page , perPage , searchAfter : undefined } ) , data : [ ] , page , per_page : perPage , total : respose . count , } ; } } } ;