import { DocumentNode , FragmentDefinitionNode } from 'graphql' ; import { WatchFragmentOptions , WatchFragmentWhereOptions } from './types' ; import { InvalidationPolicyCache } from '../cache' ; import { Policies } from '@apollo/client/cache/inmemory/policies' ; import { makeReference } from '@apollo/client/core' ; function _generateQueryFromFragment ( { fieldName , fragmentDefinition , } ) { return { kind : 'Document' , definitions : [ { directives : [ ] , variableDefinitions : [ ] , kind : 'OperationDefinition' , operation : 'query' , selectionSet : { kind : 'SelectionSet' , selections : [ { arguments : [ ] , kind : "Field" , name : { kind : "Name" , value : fieldName } , directives : [ { arguments : [ ] , kind : 'Directive' , name : { kind : "Name" , value : "client" } , } , ] , selectionSet : fragmentDefinition . selectionSet , } , ] } , } ] , } ; } export function buildWatchFragmentQuery ( options ) { const { fragment , id , policies , fieldName } = options ; const fragmentDefinition = fragment . definitions [ 0 ] as FragmentDefinitionNode ; const query = _generateQueryFromFragment ( { fragmentDefinition : fragmentDefinition , fieldName , } ) ; if ( ! policies . getFieldPolicy ( 'Query' , fieldName ) ) { policies . addTypePolicies ( { Query : { fields : { [ fieldName ] : { read ( _existing ) { return makeReference ( id ) ; } } } } } ) ; } return query ; } export function buildWatchFragmentWhereQuery < FragmentType > ( options ) { const { fragment , filter , policies , cache , fieldName , } = options ; const fragmentDefinition = fragment . definitions [ 0 ] as FragmentDefinitionNode ; const __typename = fragmentDefinition . typeCondition . name . value ; const query = _generateQueryFromFragment ( { fragmentDefinition , fieldName , } ) ; if ( ! policies . getFieldPolicy ( 'Query' , fieldName ) ) { policies . addTypePolicies ( { Query : { fields : { [ fieldName ] : { read ( _existing ) { return cache . readReferenceWhere ( { __typename , filter , } ) ; } } } } } ) ; } return query ; }