Okay so this is a theoretical question so I don’t have any code to show. Consider that I have GraphQL types like so:
type A {
field1: String!
field2: B!
}
type B {
fieldB1: Int!
fieldB2: C!
aRef: A!
}
type C {
fieldC1: Boolean!
fieldC2: D!
bRef: B!
}
So my question is that given a query which can enter some point in my graph. How do I prevent clients from travelling that graph to an arbitrary depth and asking for way more data than they should. Is there any way to restrict how many relationships a query can navigate ? Can I control this on server side ? How do I stop queries which can navigate from A to B to C to D and so forth without restriction ?
>Solution :
The current GraphQL specification (which can be read https://spec.graphql.org/) does not have depth limit features defined as part of the spec.
However, many GraphQL server implementations support a depth limit to prevent cyclic queries – or there are packages which does this (for example graphql-depth-limit for NodeJS)
The keyword you want to search for is depth limit for GraphQL.
A good read is an article GraphQL Cyclic Queries and Depth Limiting:
Many GraphQL implementations provide a specific parameter that you just have to set to a given value so that queries that exceed this depth level are automatically ignored by the GraphQL engine, without even starting the evaluation.
There are several ways to proceed, depending on the GraphQL engine you use:
Apollo, Express GraphQL, GraphQL Node