Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested comments in a graphql query

Tags:

graphql

apollo

I was trying to find info, but I didn't understand answers, so I'm here. I need to make a infinite nested comments system, but the thing is — i need to write everytime "children" to my schema over and over again to get childrens, but is there a way to make it recursively?

 query GetComments($postId: Int!, $skip: Int!, $take: Int!) {
    getComments(postId: $postId, skip: $skip, take: $take) {
      id
      createdAt
      updatedAt
      authorId
      comment
      parentId
      postId
      author {
        name
        id
        image
        admin
        moder
      }
      children {
        id
        createdAt
        updatedAt
        authorId
        comment
        parentId
        postId
        author {
          name
          id
          image
          admin
          moder
        }
      
      }
    }
  }

So you see that if I want to extract new children inside a children I need to write more children.

typedefs:

type User {
    id: Int
    name: String
    image: String
    admin: Boolean
    moder: Boolean
}
type Comment {
  id: String
  createdAt: String
  updatedAt: String
  authorId: Int
  comment: String
  postId: Int
  author: User
  parentId: String
  children: [Comment]
}
like image 559
Netty Avatar asked Mar 09 '26 18:03

Netty


2 Answers

The goal of GraphQL is to get data which is absolutely necessary. Hence, GraphQL doesn't support recursion. If you are in a position wherein you need to recursively fetch GraphQL data, you need to change the logic by revisiting the model as it is against what GraphQL stands for.

You can refer here, https://github.com/graphql/graphql-spec/issues/91#issuecomment-206743676

like image 98
Mahesh Avatar answered Mar 11 '26 20:03

Mahesh


NO. Recursion is an anti-pattern.

GraphQL schema should be directed acyclic graph (DAG). This means the schema should have no cycles (recursions).

If your schema contains cycles, this would mean the use cases are not properly defined. If you think in Graphs, you need to

Build your GraphQL schema to express "how" rather than "what"

like image 25
Joseph D. Avatar answered Mar 11 '26 21:03

Joseph D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!