post picture
Write Better GraphQL "where" Queries with Hasura
Published: 12 October 2022

There is a smart trick when writing GraphQL where-queries with Hasura that some developers get wrong.

Instead of making the query generic and flexible, they make it specific and unflexible.

Let me show you an example.

Here’s a query to get a list of people. With the query, you can define age and nameLike as variables.

query getPeople($age: Int!, $nameLike: String!) {
  people(
    where: { _and: [{ age: { _eq: $age } }, { name: { _like: $nameLike } }] }
  ) {
    id
    name
  }
}

With the following variables:

{
  "age": 33,
  "nameLike": "%Jo%"
}

The problem with this approach is that it’s inflexible and you can only use the query for one specific task. If you want to filter on something other than age and nameLike you need to write new GraphQL queries.

That’s not optimal.

It’s better to write a generic and flexible where.

Like this:

query getPeople($where: people_bool_exp!) {
  people(where: $where) {
    id
    name
  }
}

With the following variables:

{
  "where": {
    "_and": [
      {
        "age": {
          "_eq": 33
        }
      },
      {
        "name": {
          "_like": "%Jo%"
        }
      }
    ]
  }
}

This way, you can re-use the same query for different boolean expressions by changing the where expression using the GraphQL variable.

PS. Star us on GitHub

Do you like what we're building?

Star us on GitHub ⭐

Thank you.

We use cookies to provide our services and for analytics and marketing. By continuing to browse our website, you agree to our use of cookies.
To find out more about our use of cookies, please see our Privacy Policy and Cookies Policy.