如何在GraphQL查询中有条件地包含参数? [英] How to conditionally include an argument in a GraphQL query?
问题描述
我有以下GraphQL查询(使用Apollo Client JS):
I have the following GraphQL query (using Apollo Client JS):
query GetUsers($searchFilter: String) {
users(
first: 10,
filter: { search: $searchFilter }
) {
nodes {
id
name
}
}
}
当我传入 $ searchFilter
参数时,此方法效果很好.但是,我希望此 $ searchFilter
参数为可选.因此,当它为 null
时,它不会应用该过滤器.
This works well when I pass in the $searchFilter
argument. However, I want this $searchFilter
argument to be optional. So when it's null
it doesn't apply the filter.
这似乎很简单,但是API要求 search
不可为空.因此,不允许传入 filter:{搜索:null}
.
This seems simple enough, but the API requires the search
to be non-nullable. So passing in filter: { search: null }
is not allowed.
我想实现以下目标:
query GetUsers($searchFilter: String) {
users(
first: 10,
filter: $searchFilter = null ? null : { search: $searchFilter }
) {
nodes {
id
name
}
}
}
如何有条件地包含 filter
参数?
How do I conditionally include the filter
argument?
推荐答案
只需传递(整个早先组成/准备好"的)值作为 filter
(在查询时定义)变量.将此变量保留为未定义状态即可.
Just pass (entire 'composed/prepared earlier') value for filter
(define at query) variable. Leaving this variable undefined makes it optional.
query GetUsers($filter: SomeFilterInputType) {
users(
first: 10,
filter: $filter ) {
在[query]变量中为 filter
传递
值:
pass value for filter
in [query] variables:
{
filter: { search: 'sth'}
}
...,其中 SomeFilterInputType
是[ users
query] arg类型名称,可以从graphiql/playground文档中提供的API规范中读取...或服务器代码/类型defs
... where SomeFilterInputType
is a [users
query] arg type name, it can be read from API specs, available in graphiql/playground docs ... or server code/type defs
可以使用QUERY VARIABLES在graphiql/playground中对其进行测试.
It can be tested in graphiql/playground using QUERY VARIABLES.
变量
是具有相同结构的对象,可以有条件地轻松创建/修改.
variables
passed from JavaScript is an object with the same structure, easily created/modified conditionally.
在这种情况下, SomeFilterInputType
(类型名称后没有!
标记)表示可以将其( filter
变量)设置为空/未定义-通常可选的args可以为空(不是必需的).如果API/BE规范中需要一些arg,则客户端中也必须使用它.
In this case SomeFilterInputType
(no !
mark after type name) means it (filter
variable) can be nulled/undefined - usually optional args are nullable (not required). If some arg is required in API/BE specs then it must be required in client, too.
这篇关于如何在GraphQL查询中有条件地包含参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!