Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to graphql fragment?

It's easy to pass a parameter to a GraphQL query. But what about GraphQL fragments?

This code contains some perfectly normal querying with a parameter (itemId) and a hint at what I attempt to do (includeExtraResults) :

export const GET_ITEM = gql`
  query GetItem($itemId: ID!, $includeExtraResults:BOOLEAN) {
    container {
      item(itemId: $itemId) {
        itemId
        someField
        innerItem(someExtraOption: $includeExtraResults) {
          ...InnerItemFragment
        }
      }
    }
  }
  ${INNER_ITEM_FRAGMENT}
`;

export const INNER_ITEM_FRAGMENT = gql`
  fragment InnerItemFragment on InnerItemType {
    innerItemId
    innerInnerItem(someExtraOption: $includeExtraResults) {
      someFields
    }
  }
  ${INNER_INNER_ITEM_FRAGMENT}
`;


export const INNER_INNER_ITEM_FRAGMENT = gql`
  /* (not detailed here) */
`;

When inner-inner items get automatically queried as part of inner items, I don't want them to return the field based upon which the filter works. The client doesn't know the logic either. Instead I want to use the parameter, and the logic is decided on server side.

Still, their query is implemented in a way that it wants the (optional) parameter "includeExtraResults", which is passed to GetItem in the first place.

So, is there a way to pass "includeExtraResults" to the inner fragment? What should be changed for this to make sense? In real life this is a complex system with many levels of inner fragments.

like image 255
jeancallisti Avatar asked Mar 29 '19 10:03

jeancallisti


2 Answers

It's not the same, but still related:

You can use query's variables inside Fragments:

query HeroComparison($first: Int = 3) {
  leftComparison: hero(episode: EMPIRE) {
    ...comparisonFields
  }
  rightComparison: hero(episode: JEDI) {
    ...comparisonFields
  }
}

fragment comparisonFields on Character {
  name
  friendsConnection(first: $first) {
    totalCount
    edges {
      node {
        name
      }
    }
  }
}

This info from the official guide

like image 110
Ilya Iksent Avatar answered Oct 21 '22 01:10

Ilya Iksent


As outlined here, you have to explicitly enable fragment variables before using them:

import { enableExperimentalFragmentVariables } from 'graphql-tag'

enableExperimentalFragmentVariables()

That should at least let you use variables defined in your operation inside included fragments. Please note that this still is an experimental feature that's not officially part of the spec -- see this issue for the ongoing conversation.

like image 38
Daniel Rearden Avatar answered Oct 21 '22 02:10

Daniel Rearden