Search code examples
node.jsexpressgraphqlgraphiql

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


Solution

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