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?
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With