When we need to use GraphQL to query multi-level nested data, such as nested comment information like WordPress, the usual writing method is:

 { posts(first: 100) { nodes { id title comments { nodes { ...CommentFields replies: children { nodes { ...CommentFields replies: children { nodes { ...CommentFields replies: children { nodes { ...CommentFields replies: children { nodes { ...CommentFields } } } } } } } } } } } } } fragment CommentFields on Comment { id date type approved content }

The above writing method only implements the query of four layers of nested comments, which is troublesome, right? This may be the defect of GraphQL, but it may also reflect the design philosophy of GraphQL - what you get is what you check.

After searching, if there is no ready-made wheel, just write a nested implementation (note that graphql query statements should be written first, and extra indentation will affect the recursive results):

 import ApolloClient from 'apollo-boost' import gql from 'graphql-tag' class getPostCommentByPostId { private postId: number private MaxChildrenLevel: number private data: any /** * @param {number} postId           wordpress post id * @param {number} MaxChildrenLevel post threaded (nested) comments levels deep (/wp-admin/options-discussion.php) */ public constructor(postId: number, MaxChildrenLevel) { this.postId = postId this. MaxChildrenLevel = MaxChildrenLevel } //Processing recursive parts private queryChildren() { let queryHeader: string = `` let queryFooter: string = `` //Content before iteration const childrenHeader: string = ` children { nodes { ...CommentFields` //Contents after iteration const childrenFooter: string = ` } }` //Process space before each line let addTabs = function (str: string, n: number) { Return str. replace (/^/gm, ''. repeat (n)) } for (let i = 0; i < this.MaxChildrenLevel; i++) { queryHeader = addTabs(childrenHeader + queryHeader, 2) queryFooter = addTabs(queryFooter + childrenFooter, 2) } return addTabs(queryHeader + queryFooter, 2) } //Query section private query() { const client: ApolloClient = new ApolloClient() client.query({ query: gql` query GET_POST($postId: Int) { postBy(postId: $postId) { id postId title date uri content } comments { edges { node { ...CommentFields${this.queryChildren()} } } } } fragment CommentFields on Comment { date agent content(format: RENDERED) commentId author { ... on CommentAuthor { email name url } } authorIp } `, variables: { "postId": this.postId }, }) .then(data => console.log(data)) .catch(error => console.log(error)) } }

Q.E.D.

Appreciation