import { ApolloClient , ApolloClientOptions , DocumentNode , ObservableQuery , } from '@apollo/client/core' ; import { Policies } from '@apollo/client/cache/inmemory/policies' ; import { buildWatchFragmentQuery , buildWatchFragmentWhereQuery } from './utils' ; import { InvalidationPolicyCache } from '../cache' ; import { WatchFragmentOptions , WatchFragmentWhereOptions } from './types' ; import { generateFragmentFieldName } from '../helpers' ; export default class ApolloExtensionsClient < TCacheShape > extends ApolloClient < TCacheShape > { protected policies : Policies ; constructor ( config ) { super ( config ) ; this . policies = this . cache . policies ; } private watchQueryForField ( query , fieldName ) { const obsQuery = this . watchQuery ( { fetchPolicy : 'cache-only' , query : query , } ) ; const subscribe = obsQuery . subscribe . bind ( obsQuery ) ; obsQuery . subscribe = ( observer ) => { if ( typeof observer != 'object' ) { observer = { next : observer , error : arguments [ 1 ] , complete : arguments [ 2 ] , } ; } const observerNext = observer . next ; observer . next = ( value ) => { if ( observerNext ) { observerNext ( value ?. data ?. [ fieldName ] ) ; } } ; const subscription = subscribe ( observer ) ; const unsubscribe = subscription . unsubscribe . bind ( subscription ) ; subscription . unsubscribe = ( ) => { delete this . cache . policies . typePolicies . Query . fields [ fieldName ] ; unsubscribe ( ) ; } ; return subscription ; } ; return obsQuery ; } watchFragment ( options ) { const fieldName = generateFragmentFieldName ( ) ; const query = buildWatchFragmentQuery ( { ... options , fieldName , policies : this . policies , } ) ; return this . watchQueryForField ( query , fieldName ) ; } watchFragmentWhere < FragmentType > ( options ) { const fieldName = generateFragmentFieldName ( ) ; const query = buildWatchFragmentWhereQuery ( { ... options , fieldName , cache : this . cache as unknown as InvalidationPolicyCache , policies : this . policies , } ) ; return this . watchQueryForField ( query , fieldName ) ; } }