import { IIndexPattern } from '../../index_patterns' ; import { OpenSearchQuerySortValue , SortOptions } from './types' ; export function normalizeSortRequest ( sortObject , indexPattern , defaultSortOptions = { } ) { const sortArray = Array . isArray ( sortObject ) ? sortObject : [ sortObject ] ; return sortArray . map ( function ( sortable ) { return normalize ( sortable , indexPattern , defaultSortOptions ) ; } ) ; } /**
 * Normalize the sort description to the more verbose format (e.g. { someField: "desc" } into
 * { someField: { "order": "desc"}}), and convert sorts on scripted fields into the proper script
 * for OpenSearch. Mix in the default options according to the advanced settings.
 */ function normalize ( sortable , indexPattern , defaultSortOptions ) { const [ [ sortField , sortOrder ] ] = Object . entries ( sortable ) ; const order = typeof sortOrder === 'object' ? sortOrder : { order : sortOrder } ; if ( indexPattern && typeof indexPattern !== 'string' ) { const indexField = indexPattern . fields . find ( ( { name } ) => name === sortField ) ; if ( indexField && indexField . scripted && indexField . sortable ) { return { _script : { script : { source : indexField . script , lang : indexField . lang , } , type : castSortType ( indexField . type ) , ... order , } , } ; } } const { unmapped_type , ... otherSortOptions } = defaultSortOptions ; return { [ sortField ] : { ... order , ... ( sortField === '_score' ? otherSortOptions : defaultSortOptions ) } , } ; } function castSortType ( type ) { if ( [ 'number' ] . includes ( type ) ) { return 'number' ; } else if ( [ 'string' , 'boolean' ] . includes ( type ) ) { return 'string' ; } throw new Error ( `Unsupported script sort type: ${ type }` ) ; }