如何将字段列表片段插值移到括号外

How to move fields list fragment interpolation outside of the brackets

这是我正在使用的当前 graphQL 的模拟。

const aDynamicListOfFieldsComingFromElsewhere = 'foo bar anotherField etc'

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

这...从功能上讲,有效。但由于多种原因被认为是一种糟糕的方法,其中之一是 eslint-plugin-graphql 提供的 linting 支持。

Eslint 提示我以下错误:

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

我设法找到了一些很好的变量示例,但是 none 提供了一种包含外部定义变量的方法。

在此先感谢您的帮助!

您可以为此使用指令。 GraphQL 规范:https://graphql.org/learn/queries/#directives

查询应如下所示:

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)
    }
  }
`

还有应该传递到您的 GraphQL 客户端的变量:

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