Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursive object as a graphql field #3531

Closed
Tbaut opened this issue Dec 13, 2019 · 2 comments
Closed

Recursive object as a graphql field #3531

Tbaut opened this issue Dec 13, 2019 · 2 comments

Comments

@Tbaut
Copy link

Tbaut commented Dec 13, 2019

Is there a way to add a recursive object type as a field as explained here: graphql/graphql-spec#91 (comment) ?
The idea is to have replies on comments in a forum (like reddit, you can reply to a comment, which can be replied to etc.)

So that I could do the following query:

{
  messages {
    ...CommentsRecursive
  }
}

fragment CommentsRecursive on Message {
  comments {
    ...CommentFields
    comments {
      ...CommentFields
      comments {
        ...CommentFields
      }
    }
  }
}

fragment CommentFields on Comment {
  id
  content
}

In the link I posted above, managing your own graphql server, they achieve it by using a function as a field that returns some other fields:

const Message = new GraphQLObjectType({
  name: 'Message',
  fields: () => ({
    comments: {
      type: new GraphQLList(Message),
      resolve(message) {
        return getComments(message.id);
      },
    },
    content: {
      type: GraphQLString,
    },
  }),
});

I wonder how I could achieve something similar with hasura.

@Tbaut Tbaut changed the title Reccursive object as a graphql field Recursive object as a graphql field Dec 14, 2019
@ecthiender
Copy link
Member

You can have a Postgres table which is recursive.

E.g. -

CREATE TABLE messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  content text NOT NULL,
  parent_message UUID REFERENCES messages(id)
);

Then in the Hasura console, if you go to the relationships tab of the messages table, you can see that both object and array relationships are suggested on the same table. You can add them both, name the object relationship as parent and the array relationship as children.

Now you can make the following query:

query {
  messages {
    id 
    content
    children {
      id
      content
    }
  }
}

This fetches all messages and all their children.

PS: beware that this query can be quite expensive on large data set. You would add limits etc. when using the query in production.

@Tbaut
Copy link
Author

Tbaut commented Dec 15, 2019

Thank you so much. A simple foreign key is indeed doing the job perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants