Search code examples
graphqlhasura

How to use previously acquired data in the GraphQL query?


Let's say we have two entities.

  • users that has uuid, name and age
  • users_books that has user_uuid, book_id and recommended_age.

user_uuid was added as foreign key pointing to uuid in Users

Using user name I want to get all the books that that user reads and have recommended age equal to users age.

Following query will get me all the books that user reads

query getUserBooks($uuid: uuid!) {
  users_by_pk(uuid: $uuid) {
    uuid
    name
    age
    users_books() {
       book_id
       recommended_age
    }
  }
}

And this is the query I am trying to create:

query getUserBooksWithRestrictedAge($uuid: uuid!) {
  users_by_pk(uuid: $uuid) {
    uuid
    name
    age
    users_books(where:{recommended_age:{_eq: *WHAT_SHOULD_GO_HERE?*}}) {
       book_id
       recommended_age      
    }
  }
}

Is this even possible?


Solution

  • Hasura supports columns comparison operators only when setting permissions. To accomplish what you need you have to create a view.

    CREATE OR REPLACE VIEW users_books_by_age AS 
      SELECT * from users_books
    

    Set the relationships between the view, user and books table. In the Hasura view permission builder filter the age comparing the columns. Something like

    {
      user: {
        age: {
         _ceq: recommended_age
        }
      }
    }
    

    This way you can run your query like:

    query getUserBooks($uuid: uuid!) {
      users_by_pk(uuid: $uuid) {
        uuid
        name
        age
        users_books_by_age {
           book_id
           recommended_age
        }
      }
    }
    

    Another solution would be to create a computed field. Something like:

    CREATE FUNCTION author_full_name(user_row user)
    RETURNS SETOF users_books AS $$
      SELECT * FROM users_books where recommended_age = user_row.age
    $$ LANGUAGE sql STABLE;
    

    I hope that helps.