Structuring GraphQL Types

I had a problem trying to extend the API to include the GraphQL endpoint. The application I'm working on is a kind of forum with Messages. A message may contain type comments Message. If the post is a comment, it has a parent type Message. Simplified, the scheme looks like this:

type Message {
  id: String
  content: String
  comments: [Message]
  parent: Message
}

type RootQuery {
  message(id: String): Message
  messages: [Message]
}

The problem with this scheme is that it allows you to query such requests:

{
  messages {
    comments {
      parent {
        comments {
          parent {
            comments {
              parent {
                id
                content       
              }
            }       
          }
        }   
      }
    }
  }
}

Keep in mind that I can allow arbitrarily deep nesting of comments. In this case, the following request should be allowed:

{
  messages {
    comments {
      comments {
        comments {
          id
          content
        }
      }
    }
  }
}

So my question is this: should I introduce a new type - comment - an API that does not know its parent? Or are there other ways to limit this kind of unwanted behavior?

, Comment fragment messageFields on Message ? , ?

, ( ):

interface Message {
  id: String
  content: String
  comments: [Message]
}

type DefaultMessage : Message {
  id: String
  content: String
  comments: [Comment]
  parent: Message
}

type Comment : Message {
  id: String
  content: String
  comments: [Message]
}

type RootQuery {
  message(id: String): Message
  messages: [Message]
}
+4
3

- , graphql-js, graphql-js:

 * When two types need to refer to each other, or a type needs to refer to
 * itself in a field, you can use a function expression (aka a closure or a
 * thunk) to supply the fields lazily.
 *
 * Example:
 *
 *     var PersonType = new GraphQLObjectType({
 *       name: 'Person',
 *       fields: () => ({
 *         name: { type: GraphQLString },
 *         bestFriend: { type: PersonType },
 *       })
 *     });
 *
 */

https://github.com/graphql/graphql-js/blob/master/src/type/definition.js#L274

+3

, .

, parent type Comment, DefaultMessage. parent - comments - parent, DDOS, , , API REST, .

. , comment , ? , , GraphQL .

, , , ( X ), , node

{
  messages {
    comments {
      id
      content
    }
  }
}

{
  node(commendId) {
    comment {
      id
      content
    }
  }
}
0

I assume that you have deptha data structure attribute Commentthat should be very useful, for example, to limit the maximum nested depth when users post comments.

So that your problem can be solved as follows: in the resolverattribute commentscheck the box depth, don’t return anything if it depthbecomes illegal, otherwise you will receive comments and a refund.

0
source

Source: https://habr.com/ru/post/1606288/


All Articles