graphql - 如何将字段列表片段插值移动到括号之外
问题描述
这是我正在使用的当前 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
我设法找到了一些带有变量的好例子,但没有一个提供包含外部定义变量的方法。
在此先感谢您的帮助!
解决方案
您可以为此使用指令。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
}