How to move fields list fragment interpolation outside of the brackets

Viewed 415

Here is a mock of the current graphQL I'm working with.

const aDynamicListOfFieldsComingFromElsewhere = 'foo bar anotherField etc'

const query = gql`{
  QueryResult: TableName {
    Data {
      id
      name
      ${aDynamicListOfFieldsComingFromElsewhere}
    }
  }
}`

This... functionally speaking, works. But is regarded as a bad approach for multiple reasons, one of which is the linting support provided by eslint-plugin-graphql.

Eslint gives me a hint by giving me the following error:

Invalid interpolation - fragment interpolation must occur outside of the brackets  graphql/template-strings

I managed to find some good examples with variables, but none that provided a way to include an externally defined variable.

Thanks in advance for your help!

1 Answers

You can use directives for this. Specification for GraphQL: https://graphql.org/learn/queries/#directives

Query should looks like this:

const query = gql`
  query QueryResult($withFoo: Boolean!, $withBar: Boolean!, $withAnotherField: Boolean!, $withEtc: Boolean!) {
    Data {
      id
      name
      foo @include(if: $withFoo)
      bar @include(if: $withBar)
      anotherField @include(if: $withAnotherField)
      etc @include(if: $withEtc)
    }
  }
`

And also the variables that should be passed into your GraphQL client:

{
   withFoo: true, 
   withBar: true, 
   withAnotherField: false,
   withEtc: true
}
Related