Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

javascript - How to conditionally include an 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...