import uuid from 'uuid' ; import { ElasticsearchClient } from 'kibana/server' ; import type { DeserializerOrUndefined , MetaOrUndefined , SerializerOrUndefined , Type , } from '@kbn/securitysolution-io-ts-list-types' ; import { transformListItemToElasticQuery } from '../utils' ; import { CreateEsBulkTypeSchema , IndexEsListItemSchema } from '../../schemas/elastic_query' ; export interface CreateListItemsBulkOptions { deserializer : DeserializerOrUndefined ; serializer : SerializerOrUndefined ; listId : string ; type : Type ; value : string [ ] ; esClient : ElasticsearchClient ; listItemIndex : string ; user : string ; meta : MetaOrUndefined ; dateNow ? : string ; tieBreaker ? : string [ ] ; } export const createListItemsBulk = async ( { listId , type , deserializer , serializer , value , esClient , listItemIndex , user , meta , dateNow , tieBreaker , } ) : Promise < void > => { if ( ! value . length ) { return ; } const body = value . reduce < Array < IndexEsListItemSchema | CreateEsBulkTypeSchema > > ( ( accum , singleValue , index ) => { const createdAt = dateNow ?? new Date ( ) . toISOString ( ) ; const tieBreakerId = tieBreaker != null && tieBreaker [ index ] != null ? tieBreaker [ index ] : uuid . v4 ( ) ; const elasticQuery = transformListItemToElasticQuery ( { serializer , type , value : singleValue , } ) ; if ( elasticQuery != null ) { const elasticBody = { created_at : createdAt , created_by : user , deserializer , list_id : listId , meta , serializer , tie_breaker_id : tieBreakerId , updated_at : createdAt , updated_by : user , ... elasticQuery , } ; const createBody = { create : { _index : listItemIndex } } ; return [ ... accum , createBody , elasticBody ] ; } else { return accum ; } } , [ ] ) ; try { await esClient . bulk ( { body , index : listItemIndex , refresh : 'wait_for' , } ) ; } catch ( error ) { } } ;