6. 查询变量
当我们组织 GraphQL
查询语句时,会很自然地使用参数。同时也会很自然地硬编码它们。
{
recentAppointmentRequests(count: 10) {
_id,
}
}
比如说我们需要把 count
修改为 20
。然后我们需要再次生成查询。这会增加 app
的维护成本。
使用这样的方法,我们无法在服务器端设置这些参数。通常在典型的应用中,userId
是必须在服务器端设置的参数。
但是幸运的是,GraphQL
有将值传给 query
更好的方式,而不是在 query
中硬编码它们。这就是 查询变量 的任务。
命名 queries
在之前的课程中,我们使用精简的语法定义 GraphQL queries
。
{
recentAppointmentRequests(count: 10) {
_id
}
}
但是这是写查询完整的语法:
query getFewAppointmentRequests {
recentAppointmentRequests(count: 10) {
_id
}
}
这里我们使用了 query
关键字,并命名了这个 query
。你可以输入任意名字。相比完整的语法,在精简的版本中,我们简单地忽略了 query getFewAppointmentRequests
部分。
我们需要使用 查询变量 来写具有完整语法的 queries
。
使用 查询变量
比如我们需要对 count
参数使用 查询变量 。
query getFewAppointmentRequests {
recentAppointmentRequests(count: 10) {
_id
}
}
// 这么写
query getFewAppointmentRequests($appointmentRequestCount: Int!) {
recentAppointmentRequests(count: $appointmentRequestCount) {
_id
}
}
这里,我们定义了 Int
类型的 appointmentRequestCount
查询变量 。我们同时使用末尾的 !
来表明它为必传变量。
我们需要使得
appointmentRequestCount
的 查询变量 必传,这是因为对于recentAppointmentRequests
参数而言,appointmentRequestCount
是必传参数。
如何输入 查询变量
你可能对如何提供 查询变量 有疑问。
我们通常在执行服务器查询的时候提供查询变量。我们先不用考虑它的实现原理,我们会在后面的课程讲到。
在GraphQL Sandbox
中,我们有独立的 tab
来写查询变量。如下图:
现在你可以尝试着在GraphQL Sandbox
中使用查询变量了,我们添加以下JSON
到查询变量的tab
中:
{
"appointmentRequestCount": 2
}
简单的问题,如果你不给查询变量appointmentRequestCount
赋值会发生什么?(从查询变量 tabs
中移除appointmentRequestCount
字段):
在查询语句的任意位置使用查询变量
一旦定义了查询变量,我们可以在 query
的任意位置使用它。这是我们在字段参数中使用它的例子:
query getFewAppointmentRequests($appointmentRequestCount: Int!, $patientCount: Int) {
recentAppointmentRequests(count: $appointmentRequestCount) {
_id,
patients(limit: $patientCount) {
name
}
}
}
我们也能在 fragment
中使用它:
query getFewAppointmentRequests($appointmentRequestCount: Int!, $patientCount: Int) {
recentAppointmentRequests(count: $appointmentRequestCount) {
_id,
...patients
}
}
fragment patients on Post {
patients(limit: $patientCount) {
name
}
}
你同样能在 Mutation
中使用它。
Input type
在 GraphQL Schema
中,会有不同的类型,其中包括内置类型(比如: init
、string
)和自定义类型(比如: Post
、Author
)。但是对于查询变量,我们不能全用。
我们仅能使用一部分类型,它们被称为 Input type
。
通常 Input type
包括:
- Scalers such as Int, String, Float and Boolean
- Enums
- Arrays of the above types.
可以通过 GraphQL标准
来了解更多的 Input type
。
看一下这条query
:
query getFewAppointmentRequests($type: appointmenttype) {
appointmentRequests(type: $type) {
_id
}
}
这里我们尝试通过 type
过滤预约挂号记录,type
参数是 appointmenttype
的枚举值。 expert专家
,department专科
是其中之一。所以你可以像这样定义查询变量:
{
"type": "expert"
}
以下列表,哪种 type
是不存在的:
- METEOR
- OTHER
- USER_STORY
- GRAPHQL ✔️
最后
现在我们了解了查询变量,以及以不同的方式使用它。当你在客户端使用GraphQL
时,查询变量会非常有用。