import { ElasticsearchClient } from 'kibana/server' ; import { schema , TypeOf } from '@kbn/config-schema' ; import { IndexSettings , LegacyTemplateSerialized , TemplateFromEs , } from '../../../../../index_management/common/types' ; import { RouteDependencies } from '../../../types' ; import { addBasePath } from '../../../services' ; function isReservedSystemTemplate ( templateName , indexPatterns ) { return ( templateName . startsWith ( 'kibana_index_template' ) || ( templateName . startsWith ( '.' ) && indexPatterns . every ( ( pattern ) => { return ! pattern . includes ( '*' ) ; } ) ) ) ; } function filterLegacyTemplates ( templates ) { const formattedTemplates = [ ] ; const templateNames = Object . keys ( templates ) ; for ( const templateName of templateNames ) { const { settings , index_patterns } = templates [ templateName ] ; if ( isReservedSystemTemplate ( templateName , index_patterns ) ) { continue ; } const formattedTemplate = { settings , name : templateName , } ; formattedTemplates . push ( formattedTemplate ) ; } return formattedTemplates ; } function filterTemplates ( templates , isLegacy ) { if ( isLegacy ) { return filterLegacyTemplates ( templates as { [ templateName ] : LegacyTemplateSerialized ; } ) ; } const { index_templates : indexTemplates } = templates as { index_templates : TemplateFromEs [ ] ; } ; return indexTemplates . map ( ( template ) => { return { name : template . name , settings : template . index_template . template ?. settings } ; } ) ; } async function fetchTemplates ( client , isLegacy ) { const options = { ignore : [ 404 ] , } ; const response = isLegacy ? await client . indices . getTemplate ( { } , options ) : await client . indices . getIndexTemplate ( { } , options ) ; return response . body ; } const querySchema = schema . object ( { legacy : schema . maybe ( schema . oneOf ( [ schema . literal ( 'true' ) , schema . literal ( 'false' ) ] ) ) , } ) ; export function registerFetchRoute ( { router , license , lib : { handleEsError } } ) { router . get ( { path : addBasePath ( '/templates' ) , validate : { query : querySchema } } , license . guardApiRoute ( async ( context , request , response ) => { const isLegacy = ( request . query as TypeOf < typeof querySchema > ) . legacy === 'true' ; try { const templates = await fetchTemplates ( context . core . elasticsearch . client . asCurrentUser , isLegacy ) ; const okResponse = { body : filterTemplates ( templates , isLegacy ) } ; return response . ok ( okResponse ) ; } catch ( error ) { return handleEsError ( { error , response } ) ; } } ) ) ; }