Skip to content
Advertisement

Optional variable in Graphql

I have a graphql query like this:

query SomeQuery($id: Int) {
  some_query(where: {id: {_eq: $id}}) {
    id
    name
  }
}

when i run this it expects a id as variable. How can I make that variable optional? It should display all results when no id is given

Advertisement

Answer

There’s no way that I’m aware to declare a variable as optional but also have it ignore the rest of the expression in the way you’re demonstrating here with Hasura.

Instead, you should define your query such that the variable you receive is the actual boolean expression and the conditionally pass in the variables from the caller. Try writing your query like this instead:

query getItems($where: items_bool_exp) {
  items(where: $where) {
    name
  }
}

This makes the filter optional so if you pass null to $where you’ll get back everything. Otherwise, you can pass in the actual filter condition as the variable and get back the result you’re expecting

{
  "where": {
    "id": {
      "_eq": 42
    }
  }
}

You’ll just have to update the client that’s actually issuing the query to use the right conditional logic regarding whether or not the predicate for the ID should be sent.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement