查询和修改(Queries and Mutations)

On this page, you'll learn in detail about how to query a GraphQL server.

 在这个页面,你将会学习更多的关于如何查询GraphQl服务。

Fields 

At its simplest, GraphQL is about asking for specific fields on objects. Let's start by looking at a very simple query and the result we get when we run it:

最简单的来说,GraphQl是在Object上请求特定的fields。让我们查看一个非常简单的查询和我们运行它的时候得到的结果:

//查询方法
{
  hero {
    name
  }
}
//运行结果
{
  "data": {
    "hero": {
      "name": "R2-D2"
    }
  }
}

You can see immediately that the query has exactly the same shape as the result. This is essential to GraphQL, because you always get back what you expect, and the server knows exactly what fields the client is asking for.

 我们可以看到查询与结果的形状非常相似。这对于GraphQl是必需的,因为你总是得到你期望的,服务器端完全知道客户端请求的fields.

The field name returns a String type, in this case the name of the main hero of Star Wars,"R2-D2".

name字段返回一个String类型,在这个例子星际战争中主要的英雄的名字:R2-D2

Oh, one more thing - the query above is interactive. That means you can change it as you like and see the new result. Try adding an appearsIn field to the hero object in the query, and see the new result.

 

 

此外,上面的查询是交互性的。这也意味着你可以按你自己的意愿去改变他并且得到他的结果。尝试为hero的Object添加一个appearsIn字段,并且查看他的新的结果。

In the previous example, we just asked for the name of our hero which returned a String, but fields can also refer to Objects. In that case, you can make a sub-selection of fields for that object. GraphQL queries can traverse related objects and their fields, letting clients fetch lots of related data in one request, instead of making several roundtrips as one would need in a classic REST architecture.

 在之前的例子中,我们仅仅是查询英雄的名字(返回一个String类型),但是fields同样可以是一个Object.在这个例子中,你可以为这个Object创建一个子部。GraphQl可以便利相关的Object以及他们的fields,假如客户端在一个请求中获取很多相关的数据,而不是像在传统的REST结构中进行好几次往返。
//查询
{
  hero {
    name
    # Queries can have comments!
    friends {
      name
    }
  }
}
//结果
{
  "data": {
    "hero": {
      "name": "R2-D2",
      "friends": [
        {
          "name": "Luke Skywalker"
        },
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia Organa"
        }
      ]
    }
  }
}

Note that in this example, the friends field returns an array of items. GraphQL queries look the same for both single items or lists of items, however we know which one to expect based on what is indicated in the schema.

 注意在这个例子中,friends fields返回一个数组。GraphQl查询返回单个或一个集合看起来是相似的,然而,我们知道期望哪个是基于schema定义的。

 

posted @ 2016-09-26 21:25  霓裳梦竹  阅读(293)  评论(0编辑  收藏  举报