import { SavedObjectAttributes , SavedObjectReference } from 'kibana/public' ; export function extractReferences ( { attributes , references = [ ] , } ) { const state = JSON . parse ( JSON . parse ( String ( attributes . wsState ) ) ) ; const { indexPattern } = state ; if ( ! indexPattern ) { throw new Error ( 'indexPattern attribute is missing in "wsState"' ) ; } state . indexPatternRefName = 'indexPattern_0' ; delete state . indexPattern ; return { references : [ ... references , { name : 'indexPattern_0' , type : 'index-pattern' , id : indexPattern , } , ] , attributes : { ... attributes , wsState : JSON . stringify ( JSON . stringify ( state ) ) , } , } ; } export function injectReferences ( savedObject , references ) { if ( typeof savedObject . wsState !== 'string' ) { return ; } const state = JSON . parse ( savedObject . wsState ) ; if ( ! state . indexPatternRefName ) { return ; } const indexPatternReference = references . find ( ( reference ) => reference . name === state . indexPatternRefName ) ; if ( ! indexPatternReference ) { throw new Error ( `Could not find reference "${ state . indexPatternRefName }"` ) ; } state . indexPattern = indexPatternReference . id ; delete state . indexPatternRefName ; savedObject . wsState = JSON . stringify ( state ) ; }