Back to Blog
Company

Write Better GraphQL "where" Queries with Hasura

12 October 2022
Transparent lines
Banner of Write Better GraphQL "where" Queries with Hasura

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.


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

With the following variables:


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

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:


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

With the following variables:


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

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.

Share this post

Twitter LogoLinkedIn LogoFacebook Logo