【问题标题】:Dynamically pass required fields into GraphQL query将必填字段动态传递到 GraphQL 查询中
【发布时间】:2020-04-06 14:53:25
【问题描述】:

我有一个查询,其中查询中的必填字段可能会更改。允许用户即时生成查询,并且用户可以选择查询中的字段。有没有办法根据用户从下拉列表中的选择将必填字段传递给查询。例如:在下面的查询 id、traveller、visaApplication 中可以替换为任何其他字段。所以我的查询必须是动态的。

{
    Travels{
      id
      traveller {
        nationality
        firstName
      }
      visaApplication {
        nationality
        city
      }
    }
  }

【问题讨论】:

    标签: graphql react-apollo graphql-js


    【解决方案1】:

    可以使用字符串插值动态添加字段:

    const otherFields = `
      traveller {
        nationality
        firstName
      }
    `
    const query = gql`
      {
        Travels {
          id
          ${otherFields}
        }
      }
    `
    

    您还可以利用 @skip@include 指令与变量结合使用,以控制在使用单个查询时是否跳过/包含特定请求的特定字段:

    const query = gql`
      query (
        $includeTraveller: Boolean!
        $includeVisa: Boolean!
      ) {
        Travels {
          id
          traveller @include(if: $includeTraveller) {
            nationality
            firstName
          }
          visaApplication @include(if: $includeVisa) {
            nationality
            city
          }
        }
      }
    `
    

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2018-11-25
      • 1970-01-01
      • 2017-10-27
      • 2019-04-06
      • 2017-09-27
      • 2019-04-02
      • 2023-01-26
      • 2018-11-27
      相关资源
      最近更新 更多