60

Pardon the naive question, but I've looked all over for the answer and all I've found is either vague or makes no sense to me. Take this example from the GraphQL spec:

query getZuckProfile($devicePicSize: Int) {
  user(id: 4) {
    id
    name
    profilePic(size: $devicePicSize)
  }
}

What is the point of naming this query getZuckProfile? I've seen something about GraphQL documents containing multiple operations. Does naming queries affect the returned data somehow? I'd test this out myself, but I don't have a server and dataset I can easily play with to experiment. But it would be good if something in some document somewhere could clarify this--thus far all of the examples are super simple single queries, or are queries that are named but that don't explain why they are (other than "here's a cool thing you can do.") What benefits do I get from naming queries that I don't have when I send a single, anonymous query per request?

Also, regarding mutations, I see in the spec:

mutation setName {
  setName(name: "Zuck") {
    newName
  }
}

In this case, you're specifying setName twice. Why? I get that one of these is the field name of the mutation and is needed to match it to the back-end schema, but why not:

mutation {
  setName(name: "Zuck") {
...

What benefit do I get specifying the same name twice? I get that the first is likely arbitrary, but why isn't it noise? I have to be missing something obvious, but nothing I've found thus far has cleared it up for me.

4

2 回答 2

46

查询名称在服务器上没有任何意义。它仅用于客户端识别响应(因为您可以在单个请求中发送多个查询/突变)。

事实上,如果这是 GraphQL 请求中唯一的东西(并且没有任何参数),您可以只发送一个匿名查询对象:

{
  user(id: 4) {
    id
    name
    profilePic(size: 200)
  }
}

这仅适用于查询,不适用于突变。

编辑:
正如@orta 下面的注释,服务器也可以使用该名称来识别持久查询。但是,这不是 GraphQL 规范的一部分,它只是顶部的自定义实现。

于 2015-12-09T17:52:27.657 回答
14

我们使用命名查询,以便可以对它们进行一致的监控,并且可以对查询进行持久存储。重复用于查询变量以填补空白。

举个例子:

query getArtwork($id: String!) {
  artwork(id: $id) {
    title
  }
}

您可以在此处针对 Artsy GraphQL API运行它

优点是每次查询都是同一个查询,而不是不同的字符串,因为查询变量是不同的位。这意味着您可以在这些查询之上构建工具,因为您可以将它们视为不可变的。

于 2018-09-27T18:15:46.800 回答