Tuesday, April 6, 2021

Hasura - querying fields conditionally

As it turns out GraphQL is great :) I know, I know,... it's an old story but with Hasura sitting on top of PostgreSQL it is a whole different world to explore.

For example, there might be times where you have some filter that might say Select variant: "A", "B", "C", "any". Previously it was kinda obvious, that you'd say the values were [ 'A', 'B', 'C', null ] which resulted in collapsing the expression to an empty object but with the advent of Hasura 2.0 this feature was removed. Are we left with nothing? Hell no!

Conditional expressions

So let's say you have a String field that you want to either query by a value or skip in the WHERE clausule completely. How would you do that if null is not traversed to {}?

First, let's make an example and then I'll exaplain everything in details.

query GetItems($field: String_comparison_exp!) {
    where: {
      field: $field
  }) {

And the accompanying variables section to go along with it:

 { field: value ? { _eq: value } : {} }

So what happened here? First, as you can see we're not passing the value of $field anymore. Instead we're passing a String_comparison_exp. This is a way of passing the actual expression in variables. Previously, in Hasura <2.0 when a value was null the actual epxpression evaluated to an empty object ({}) which in turn evaluates to TRUE in the SQL being generated. That last part still holds true, but null is no longer collapsed in Hasura 2.0. Instead you need to do that yourself. There was a ton of issues with people deleting whole content of tables and so they removed this particular functionality.

Remark: if your field is not of type String there will be an error telling you what type of expression_exp you need to use. Just read the effin error message :D.


So now you know how to manually do the collapsing and you're the boss of GraphQL again!

Happy coding!

No comments: