Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> if people just saw it is a simple alternative to REST, with a well defined set of query (GET) and mutation (PUT/POST/DELETE) endpoints, they wouldn't get caught up in all this "infinite object graph" stuff that I never hit in my day-to-day.

Can you explain this more? How can you avoid infinite graphs? If I have User {things: Thing[]} and Thing {owner: User}, you have to deal with this issue.



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

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


> 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: