Recursive / Tree Structure data using GraphQL

Rahul Rana
Webtips
Published in
2 min readOct 17, 2021

Hi Fellow Developers.

Today we are going to talk about how to resolve a recursive data structure like tree using GraphQL.

Let’s take the example of an API that returns employees from CEO to bottom employee in a hierarchy.

We can see that it’s a hierarchal structure with employe and its children i.e people who report to the person. If we don’t know how much deep it can go. so one way is to keep writing manually all fields in a query like this

You can see the problem in the above query because you need almost the same data for every child filed, it will be very tough to write these queries. I mean it will be very long. Now let’s see if we can optimise this using Fragments.

Let’s create a fragment for employees without children, one with children.

Here we have created on fragment for employees where you can always query for which fields you want, whichever fields you will enter you will get in response to the query.
Important is we have made another query employeeRecursive, it does it using other employee fragments we created earlier, spread all fields except children, we manually use children's field and spread it. This way we can go as deep as we want.

Important: this will be helpful if you know max depth and if max depth can be up to 10–15 levels. if you know it can be up to 100 levels or more. then this will not work. this is a cleaner way.
That’s how we can utilise fragments can be utilised.

Thank you for reading. Any suggestions anything are welcome.

If you want infinite depth for GraphQl queries then a better solution to redesign the structure of data

we can do something like this

Follow me on Twitter : https://twitter.com/rahulrana_95

Linkedin: https://www.linkedin.com/in/rahul-rana-b713499a/

--

--

Rahul Rana
Webtips

Application Engineer @Flock @Directi, Frontend Engineer, VanillaJs, ReactJs, Performance, Debugger.