GraphQL Conditional Queries
Asked Answered
B

2

16

I'm a newbie in GraphQL and I was wondering if there is a easy way to query with "dynamic conditions".

For exemple, on GraphiQL I can query for :

query {
  users{
    name
    age
  }
}

And It will bring me a list of all users

{
  "data": {
    "users": [
      {
        "name": "Luis Coimbra",
        "age": 15
      },
      {
        "name": "Sebastião Campagnucci",
        "age": 50
      },
      {
        "name": "Giovana Ribeiro",
        "age": 30
      }
    ]
  }
}

But is there an easy way for me to bring only, for example, users who are above 18 or any other age ?

An expected solution would be:

query {
      users{
        name
        age > 18
      }
    }

Haven't found anything like that on documentation...

Befitting answered 15/9, 2018 at 17:45 Comment(2)
Simplest - by parameters/variables like minAge, maxAge - it's resolver role to 'react' (use) conditionally when this optional parameters are defined.Sentimentalism
good question. it's not elegant, judging from the answersBeard
D
15

This is possible-it would have to be different. Your query wouldn't be a valid GQL query. Something like this would:

    {
      users(where: {age: { $gt: 18 }}){ #inspired by mongoDB query api
        name
        age
      }
    }

or maybe simpler:

   {
     users(where: {age: ">18"}}){
        name
        age
      }
   }

of course either way the resolver on the backend needs to expect this where argument on the users field and construct the DB query accordingly when it is passed. You would not find this in GraphQL docs because GraphQL itself doesn't care about that. It only showcases how to use features of GraphQL.

If you tried example projects like for example star was api, those don't have any filtering built in.

Disqualification answered 15/9, 2018 at 19:8 Comment(0)
D
3

You should send your age filter as a parameter.You might try the following one:

In your graphql file

type users {
 name: String,
 age: Int,
 ...
}

usersQuery(ageLimit: Int): [users]

also you can send '>' , '<' , '=' as a parameter. Also it seems like that

usersQuery(ageLimit: Int, ageOperator: String): [users]

and you should configure your resolver where statement with these operators. hope it helps you.

Doubleacting answered 19/9, 2018 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.