3. GraphQL Query
GraphQL
查询语言 是 GraphQL
的主要部分。在这节课中,我们将学习如何对GraphQL
服务器进行查询,以及熟悉查询语法。
我们将查询一个典型的博客应用的数据集(正如我们前面讨论过的)。现在,不用考虑 GraphQL
服务器的工作原理,以及它的 Schema
的实现。我们将只专注于查询语法,以及如何使用它。
在本节课结束后,你会对GraphQL
以及怎么写 GraphQL Query
有一定的理解。
开始吧。
Hello GraphQL
让我们写第一个 GraphQL Query
: 检索博客中最新一篇文章的标题和摘要。为了执行 Query
,我们打开GraphQL Sandbox
。
运行这句Query
:
{
latestPost {
title,
summary
}
}
然后你会看到:
{
"data": {
"latestPost": {
"title": "New Feature: Tracking Error Status with Kadira",
"summary": "Lot of users asked us to add a feature to set status for errors in the Kadira Error Manager. Now, we've that functionality."
}
}
}
使用此Query
,我们要求 GraphQL
服务器发送图的根域字段 latestpost
(也被称为“根查询字段”)。此外,我们只需要结果对象中的标题和摘要。
Get authors
这有你的第一个任务。
在我们的GraphQL Schema
中,有个根查询字段——authors
。尝试查询字段。
任务: 在GraphQL Sandbox
中使用以下查询,选择不在查询结果中的作者:
{
authors {
_id,
name,
twitterHandle
}
}
Arunoda Susiripala
Pahan Sarathchandra
Kasun Indi
Somapala Lamaya
✔️
嵌套查询
在GraphQL
中,我们可以使用嵌套查询的方式。举个例子: 我们可以使用单个GraphQL
查询,来 检索所有的文章以及它们的评论。
调用这个查询:
{
posts {
title,
summary,
comments {
content
}
}
}
通过这种方式,我们可以根据需求深入嵌套我们的graph
。
现在,我们需要 在获取所有文章的同时,获取每一篇文章的作者名字。
提示: 查看
GraphQL Schema
的Docs
部分,可以获取关于Schema
更多的信息。同时,自动补全的功能也可以帮到你。
// query正确的写法
{
posts {
title,
author {
name
},
summary,
comments {
content
}
}
}
参数
我们可以通过指定任一字段来过滤输出。此外,我们还需要根据指定类型来获取子数据集,而不是获得整个数据集。这就要用到 参数。
以从博客获取最新文章为例,查询语句如下:
{
recentPosts(count: 5) {
title
}
}
你会从博客中检索最近的五篇文章。尝试修改count
,来观察它的变化。
在这里,count
是根查询字段 recentPosts
定义好的参数。你可以在GraphQL Sandbox
的 Docs
部分进行查看。
嵌套字段的参数
就像在 根查询字段 的参数一样,您也可以为嵌套字段添加参数。举个例子,我们可以从Schema
中检索的评论数量。
- 获取最新发布的两篇文章
- 限制每篇文章的
comments
数最大为1(使用limit
)
{
recentPosts(count: 2) {
title,
comments(limit: 1) {
content
}
}
}
多字段
在的 GraphQL
查询中,我们可以写很多根查询字段。在服务端,所有的这些字段都会被并行处理,并作为一个整体返回结果。
让我们看看一个例子。同时获取最新文章和作者。
// 同时获取作者和最近文章
{
latestPost {
title
},
authors {
name
}
}
就像那样,你可以添加任意数量的根查询字段。去玩吧!
将结果赋值给变量
此时,我们看看前一步的查询结果:
{
"data": {
"latestPost": {
"title": "New Feature: Tracking Error Status with Kadira"
},
"authors": [
{
"name": "Arunoda Susiripala"
},
{
"name": "Pahan Sarathchandra"
},
{
"name": "Kasun Indi"
}
]
}
}
假设你想在一个查询中多次查询同一个根查询字段。
举个例子,我们想要将 authors
的name
和 _id
作为两个结果分别获得:
{
latestPost {
title
},
authors {
name
},
authors {
_id
}
}
// 但是,这么写,它的结果是这样的
// 它不会分两个结果返回
{
"data": {
"latestPost": {
"title": "New Feature: Tracking Error Status with Kadira"
},
"authors": [
{
"name": "Arunoda Susiripala",
"_id": "arunoda"
},
{
"name": "Pahan Sarathchandra",
"_id": "pahan"
},
{
"name": "Kasun Indi",
"_id": "indi"
}
]
}
}
}
// 如果需要分两个结果返回
// 则需要将查询结果赋值给一个变量
{
latestPost: latestPost {
title
},
authorNames: authors {
name
},
authorIds: authors {
_id
}
}