问题
I have the following GraphQL query (using Apollo Client JS):
query GetUsers($searchFilter: String) {
users(
first: 10,
filter: { search: $searchFilter }
) {
nodes {
id
name
}
}
}
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.
This seems simple enough, but the API requires the search
to be non-nullable. So passing in filter: { search: null }
is not allowed.
I would like to achieve the following:
query GetUsers($searchFilter: String) {
users(
first: 10,
filter: $searchFilter = null ? null : { search: $searchFilter }
) {
nodes {
id
name
}
}
}
How do I conditionally include the filter
argument?
回答1:
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 ) {
pass value for filter
in [query] variables:
{
filter: { search: 'sth'}
}
... 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
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.
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.
来源:https://stackoverflow.com/questions/64696988/how-to-conditionally-include-an-argument-in-a-graphql-query