How to conditionally include an argument in a GraphQL query?

不羁岁月 提交于 2021-02-17 06:00:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!