Search code examples
graphqlapollo

GraphQL: Nested queries vs root queries


I'm using Apollo GraphQL on my server, and I'm trying to design my GraphQL API. One question I have is whether or not I should prefer nested queries over root queries.

Let's examine both in this example where the current user, me, has many invitations.

Root queries

me {
    id
    name
}

invitations {
    id
    message
}

The resolver for invitations returns invitations for the current user.

Nested query

me {
    id
    name
    invitations {
        id
        message
    }
}

These should achieve the same result, except in the latter approach invitations are nested inside the user object me. My concern is whether this will work smoothly with Apollo Client and keep the cache consistent.

What is the recommended way to design GraphQL queries?


Solution

  • I'd say it really depends on the case. Personally, I treat nested properties as a context: if the API consumer wants to fetch mine notifications, then it's me { notifications { ... } }, not notifications { ... }. If it makes sense to have a top-level key, for example, there's a concept of global notifications (not user-dependent), then go for it. If every user has own notifications (which I assume is true), then me of type User should have it, as every User does. Such generalization encourages reusable thinking: an admin panel, where user(id: ...) { ... } is being used instead of me { ... }, can use the same UI code for free.

    As a rule of thumb, it's better to think about consuming that API, not providing it.