Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL: Nested queries vs root queries

Tags:

graphql

apollo

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

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 invitations being nested in the user object me using the latter approach. My concern is though if this works smoothly with Apollo Client in keeping the cache consistent.

What is the recommended way to design GraphQL queries?

like image 714
nomadoda Avatar asked Jan 03 '19 17:01

nomadoda


People also ask

Can you nest queries in GraphQL?

GraphQL queries allow us to pass in arguments into query fields and nested query objects. You can pass arguments to every field and every nested object in your query to further deepen your request and make multiple fetches.

What is the biggest disadvantage from using GraphQL?

The Main Disadvantages of GraphQLError reporting: The queries will always return an HTTP status code of 200 regardless of whether the query was successful or not. Security: When working for an API, GraphQL lets you query your requests according to your needs.

What is root query in GraphQL?

Root fields & resolvers At the top level of every GraphQL server is a type that represents all of the possible entry points into the GraphQL API, it's often called the Root type or the Query type. In this example, our Query type provides a field called human which accepts the argument id .

What are the three types of operations in GraphQL?

GraphQL works by sending operations to an endpoint. There are three types of operations: queries, mutations, and subscriptions. A query is sent through an HTTP POST call to retrieve data. A mutation is also sent through a HTTP POST and is used to modify data.


1 Answers

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.

like image 73
Radosław Miernik Avatar answered Sep 18 '22 22:09

Radosław Miernik