How would you model recursive data structures in GraphQL?

Technology CommunityCategory: GraphQLHow would you model recursive data structures in GraphQL?
VietMX Staff asked 3 years ago
Problem

I have a tree data structure that I would like to return via a GraphQL API. I have modeled the structure as something like:

type Tag{
    id: String!
    children: [Tag]
}

The problem appears when one wants to get the tags to an arbitrary depth. To get all the children to (for example) level 3 one would write a query like:

{
    tags {
        id
        children {
            id
            children {
                id
            }
        }
    }
}

Is there a way to write a query to return all the tags to an arbitrary depth?

The idea is to flatten the tree on data level using IDs to reference them (each child with it’s parent) and marking the roots of the tree, then on client side build up the tree again recursively.

type Query {
    tags: [Tag]
}

type Tag {
    id: ID!
    children: [ID]
    root: Boolean
}

Response:

{ 
    "tags": [
        {"id": "1", "children": ["2"], "root": true}, 
        {"id": "2", "children": [], "root": false}
    ] 
}