查询和修改(Queries and Mutations)

GraphQL查询入门

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定义的。

 

转载于:https://www.cnblogs.com/dream-to-pku/p/5910748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值