import { Buffer } from 'buffer' ; import { stringify } from 'querystring' ; import { Client } from '@elastic/elasticsearch' ; import { RequestBody } from '@elastic/elasticsearch/lib/Transport' ; import { Logger } from '../../logging' ; import { parseClientOptions , OpenSearchClientConfig } from './client_config' ; export const configureClient = ( config , { logger , scoped = false } ) : Client => { const clientOptions = parseClientOptions ( config , scoped ) ; const client = new Client ( clientOptions ) ; addLogging ( client , logger , config . logQueries ) ; return client ; } ; const addLogging = ( client , logger , logQueries ) => { client . on ( 'response' , ( error , event ) => { if ( error ) { const errorMessage = `[${ event . body ?. error ?. type ?? error . name }]: ${ event . body ?. error ?. reason ?? error . message }` ; logger . error ( errorMessage ) ; } if ( event && logQueries ) { const params = event . meta . request . params ; const querystring = convertQueryString ( params . querystring ) ; const url = `${ params . path }${ querystring ? `?${ querystring }` : '' }` ; const body = params . body ? `\n${ ensureString ( params . body ) }` : '' ; logger . debug ( `${ event . statusCode }\n${ params . method } ${ url }${ body }` , { tags : [ 'query' ] , } ) ; } } ) ; } ; const convertQueryString = ( qs ) : string => { if ( qs === undefined || typeof qs === 'string' ) { return qs ?? '' ; } return stringify ( qs ) ; } ; function ensureString ( body ) { if ( typeof body === 'string' ) return body ; if ( Buffer . isBuffer ( body ) ) return '[buffer]' ; if ( 'readable' in body && body . readable && typeof body . _read === 'function' ) return '[stream]' ; return JSON . stringify ( body ) ; }