import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey' ; import Boom from '@hapi/boom' ; import { getProperty , IndexMapping } from '../../../mappings' ; const TOP_LEVEL_FIELDS = [ '_id' , '_score' ] ; export function getSortingParams ( mappings , type , sortField ? , sortOrder ? ) { if ( ! sortField ) { return { } ; } const types = Array . isArray ( type ) ? type : [ type ] ; if ( TOP_LEVEL_FIELDS . includes ( sortField ) ) { return { sort : [ { [ sortField ] : { order : sortOrder , } , } , ] , } ; } if ( types . length > 1 ) { const rootField = getProperty ( mappings , sortField ) ; if ( ! rootField ) { throw Boom . badRequest ( `Unable to sort multiple types by field ${ sortField }, not a root property` ) ; } return { sort : [ { [ sortField ] : { order : sortOrder , unmapped_type : rootField . type , } , } , ] , } ; } const [ typeField ] = types ; let key = `${ typeField }.${ sortField }` ; let field = getProperty ( mappings , key ) ; if ( ! field ) { key = sortField ; field = getProperty ( mappings , sortField ) ; if ( ! field ) { throw Boom . badRequest ( `Unknown sort field ${ sortField }` ) ; } } return { sort : [ { [ key ] : { order : sortOrder , unmapped_type : field . type , } , } , ] , } ; }