import { ApolloLink } from "apollo-link" ; import { DocumentNode } from "graphql" ; import { ApolloLinkPlugin } from "./ApolloLinkPlugin" ; interface Config { operationName : string ; selectionPath : string ; addSelection : DocumentNode ; } export class AddQuerySelectionPlugin extends ApolloLinkPlugin { private config : Config ; constructor ( config ) { super ( ) ; this . config = config ; } createLink ( ) { return new ApolloLink ( ( operation , forward ) => { if ( operation . operationName !== this . config . operationName ) { return forward ( operation ) ; } this . addSelectionToQuery ( operation . operationName , operation . query ) ; return forward ( operation ) ; } ) ; } addSelectionToQuery ( operationName , query ) { if ( operationName !== this . config . operationName ) { return ; } const { addSelection , selectionPath } = this . config ; let tree = query . definitions [ 0 ] . selectionSet . selections ; const fields = selectionPath . split ( "." ) ; fieldLoop : for ( const field of fields ) { for ( const selection of tree ) { if ( selection . name . value === field ) { tree = selection . selectionSet . selections ; continue fieldLoop ; } } return ; } tree . push ( ... addSelection . definitions [ 0 ] . selectionSet . selections ) ; } }