3 ms·
I have been writing GraphQL APIs on and off for the last 5 years, and in practice haven't had many scenarios where this was an issue. In GraphQL the query for
by vinnymac 3y ago
I have been writing GraphQL APIs on and off for the last 5 years, and in practice haven't had many scenarios where this was an issue.
In GraphQL the query for the example you gave could look like this
```gql
query {
user {
things {
owner {
id
}
}
}
}
```
When resolving an array of type `Thing` for the `things` field, you would query for the user that the `owner` field represents. Rather than assuming all relations should be loaded for an owner by default, the client would specify the fields for the `owner` that it needs. Such as I have above for the owner id. Even if no fields are specified, it would be weird to assume all relations should be loaded by default.
Now if your developers are intentionally creating infinitely deep queries, then you'd solve this the same way you'd solve an infinite loop in your code today. An issue you would catch during development or CI/CD. This can be easy to catch using a linter or during review.
```gql
query {
user {
things {
owner {
things {
owner {
things { } # etc
}
}
}
}
}
}
```
To simply protect from bad parties / developers, you might use something like
https://github.com/slicknode/graphql-query-complexity https://github.com/slicknode/graphql-query-complexity
In addition you could introduce CI tools to enforce your devs stop writing such complex queries. Also see the @skip and @include directives that can further be used to control what data is queried. In practice, however, this isn't something that comes up too much. In cases where I have seen this happen, it's usually because a developer is trying to reuse fragments without considering what data they are querying, and whether they should be reusing those fragments.
https://graphql.org/learn/queries/#fragments https://graphql.org/learn/queries/#fragments
- troupo 3y ago> In practice, however, this isn't something that comes up too much. In practice this is an issue for any publicly exposed GraphQL API. That's why the only solutions to the issue are to: - either deserialize and deep inspect the query to try and figure out if it's too complex - or to only expose persisted queries, turning it into a bad replica of JSON RPC.