Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL Conditional Queries

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

like image 721
Luis Coimbra Avatar asked Sep 15 '18 17:09

Luis Coimbra


2 Answers

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.

like image 168
Capaj Avatar answered Sep 28 '22 19:09

Capaj


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.

like image 31
Berkay Kaan Avatar answered Sep 28 '22 20:09

Berkay Kaan