Search code examples
javascriptgraphqlapollo

How to conditionally include a filtering argument in a GraphQL query?


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?


Solution

  • 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.