import { SavedObjectsClientContract , SavedObjectsFindOptions } from 'opensearch-dashboards/public' ; import { SavedObject } from '../types' ; import { StringUtils } from './helpers/string_utils' ; /**
 * The SavedObjectLoader class provides some convenience functions
 * to load and save one kind of saved objects (specified in the constructor).
 *
 * It is based on the SavedObjectClient which implements loading and saving
 * in an abstract, type-agnostic way. If possible, use SavedObjectClient directly
 * to avoid pulling in extra functionality which isn't used.
 */ export class SavedObjectLoader { private readonly Class : ( id : string ) => SavedObject ; public type : string ; public lowercaseType : string ; public loaderProperties : Record < string , string > ; constructor ( SavedObjectClass , private readonly savedObjectsClient ) { this . type = SavedObjectClass . type ; this . Class = SavedObjectClass ; this . lowercaseType = this . type . toLowerCase ( ) ; this . loaderProperties = { name : `${ this . lowercaseType }s` , noun : StringUtils . upperFirst ( this . type ) , nouns : `${ this . lowercaseType }s` , } ; } param opts returns { Promise < SavedObject > } async get ( opts ? ) { const obj = new this . Class ( opts ) ; return obj . init ( ) ; } urlFor ( id ) { return `#/${ this . lowercaseType }/${ encodeURIComponent ( id ) }` ; } async delete ( ids ) { const idsUsed = ! Array . isArray ( ids ) ? [ ids ] : ids ; const deletions = idsUsed . map ( ( id ) => { const savedObject = new this . Class ( id ) ; return savedObject . delete ( ) ; } ) ; await Promise . all ( deletions ) ; } param source param id returns { source } mapHitSource ( source , id ) { source . id = id ; source . url = this . urlFor ( id ) ; return source ; } param hit returns { hit . attributes } mapSavedObjectApiHits ( hit ) { return this . mapHitSource ( hit . attributes , hit . id ) ; } param search param size param fields returns { Promise } findAll ( search = '' , size = 100 , fields ? ) { return this . savedObjectsClient . find < Record < string , unknown > > ( { type : this . lowercaseType , search : search ? `${ search }*` : undefined , perPage : size , page : 1 , searchFields : [ 'title^3' , 'description' ] , defaultSearchOperator : 'AND' , fields , } as SavedObjectsFindOptions ) . then ( ( resp ) => { return { total : resp . total , hits : resp . savedObjects . map ( ( savedObject ) => this . mapSavedObjectApiHits ( savedObject ) ) , } ; } ) ; } find ( search = '' , size = 100 ) { return this . findAll ( search , size ) . then ( ( resp ) => { return { total : resp . total , hits : resp . hits . filter ( ( savedObject ) => ! savedObject . error ) , } ; } ) ; } }