import { CRMClient } from './CRMClient' ; import { EntityMetadata , EntityFilters , AttributeMetadata , OptionsetMetadata } from './CRMDataTypes' ; import { RetrieveEntityRequest , RetrieveEntityResponse } from './Messages' ; export class MetadataUtil { private static _metadataCache = { } ; static getEntityMetadataFromCrm ( crm , entityName ) { var request = new RetrieveEntityRequest ( entityName , EntityFilters . All ) ; var response = crm . Execute ( request ) ; return response . EntityMetadata ; } static getEntityMetadata ( crm , entityName ) { if ( this . _metadataCache [ entityName ] === undefined ) { var metadata = this . getEntityMetadataFromCrm ( crm , entityName ) ; this . _metadataCache [ entityName ] = metadata ; } return this . _metadataCache [ entityName ] ; } static getAttributeMetadata ( crm , entityName , attributeName ) { var attributeMetadata = null ; var entityMetadata = this . getEntityMetadata ( crm , entityName ) ; if ( entityMetadata && entityMetadata . Attributes && entityMetadata . Attributes . length > 0 ) { for ( var i = 0 ; i < entityMetadata . Attributes . length ; i ++ ) { if ( entityMetadata . Attributes [ i ] . LogicalName == attributeName ) { attributeMetadata = entityMetadata . Attributes [ i ] ; break ; } } if ( attributeMetadata === null ) { for ( var i = 0 ; i < entityMetadata . Attributes . length ; i ++ ) { if ( entityMetadata . Attributes [ i ] . DisplayName != null && entityMetadata . Attributes [ i ] . DisplayName . UserLocalizedLabel != null && entityMetadata . Attributes [ i ] . DisplayName . UserLocalizedLabel . Label != null && entityMetadata . Attributes [ i ] . DisplayName . UserLocalizedLabel . Label . toLowerCase ( ) == attributeName . toLowerCase ( ) ) { attributeMetadata = entityMetadata . Attributes [ i ] ; break ; } } } } return attributeMetadata ; } /** Gets the optionset number value from its label value. If not found returns null */ static getOptionsetValue ( crm , entityName , attributeName , optionsetText ) { var optionsetValue = null ; var attribute = this . getAttributeMetadata ( crm , entityName , attributeName ) ; if ( attribute === null ) throw new Error ( `Attribute ${ attributeName } not found in entity '${ entityName }'` ) ; var options = ( < OptionsetMetadata > attribute . OptionSet ) . Options ; for ( var i = 0 ; i < options . length ; i ++ ) { var option = options [ i ] ; if ( option && option . Label && option . Label . UserLocalizedLabel && option . Label . UserLocalizedLabel . Label && option . Label . UserLocalizedLabel . Label === optionsetText ) { optionsetValue = option . Value ; break ; } } return optionsetValue ; } }