如何将变量传递给GraphQL以选择字段 [英] How to pass variable to GraphQL for fields to select

查看:313
本文介绍了如何将变量传递给GraphQL以选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例查询如下:

%{
      "query" => """
        query getPerson(
            $name: String!
          ){
            getPerson(name: $name) {
              id
              col1
              col2
              col3
              col3
            }
          }
      """,
      "variables" => %{
        "name" => "person_name",
      }
    }

我想动态选择字段。例如,对于一个查询,我只需要 id,col1,col2 ,而对于另一个查询 id,col1,col3 和以此类推。

I want to select the fields dynamically. For example, for one query I just need id, col1, col2 but for another query id, col1, col3 and so on. How do I use variable for fields?

下面是我尝试的不正确的方法。

Below is what I try which is not correct.

%{
          "query" => """
            query getPerson(
                $name: String!
              ){
                getPerson(name: $name) {
                  $fields
                }
              }
          """,
          "variables" => %{
            "name" => "person_name",
            "fields" => "id col1 col3",
          }
        }

graphql是我的新手。有人可以帮我正确地编写它吗?

I am new to graphql. Can anyone help me write it correctly?

推荐答案

您不能在GraphQL中本地执行此操作。变量仅提供特定的(输入)值,而不定义查询的结构。 (在大多数SQL实现中也是如此。)

You can't natively do this in GraphQL. Variables only provide specific (input) values and don't define the structure of the query. (The same thing is true in most SQL implementations.)

您可以通读GraphQL规范中的语法,以了解例如选择集;

You can read through the grammar in the GraphQL specification to see what's allowed in, for instance, a selection set; it's just not allowed to use variables in the way you suggest.

一种最小化所需的字符串操作量的替代方法是使用命名片段来打包请求字段的列表。可以发送您实际上不使用的片段。您可以将查询重组为

One alternative that minimizes the amount of string manipulation you need to do is to use named fragments to package up a list of requested fields. It's allowed to send fragments you don't actually use. You could restructure your query as

fragment PersonParts on Person { id col1 col2 col3 }
query GetPerson($name: String!) {
  getPerson(name: $name) { ...PersonParts }
}

,如果您有多个命名片段,则将其替换掉,而不是尝试动态构造字段列表。

and if you have multiple named fragments just swap that out, instead of trying to dynamically construct the field list.

这篇关于如何将变量传递给GraphQL以选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆