by striking · 6y ago · 0 comments
It's not a replacement for SQL. It's a replacement for REST. And the intent is to provide a statically typed, holistic interface and encourage best practices in API design. It's also quite nice because there are clients that plug into it and offer substantial benefits as a result, like Relay.
There are lots of ways people write resolution methods for GraphQL, and this article provides a good number of them. You can think of them as query optimization approaches if it helps. But it's not quite like SQL, where in SQL you say whatever you like and it just gets figured out. GraphQL forces an amount of intention and asks schema writers to consider the most concrete use cases possible rather than just enabling super generic ones.
GraphQL lets you write queries for objects. This fundamentally changes how you architect your app and database.
In a REST API, you turn known a finite list of known query patterns (endpoints) into DB queries, which you can test, hand-write, and optimize.
If you let end users query your object model, it takes far more work to ensure they don't do something very expensive.
Seems like it postpones premature optimisation... which is a good thing in my opinion
But, even should you have to support a complex schema, the fine article showcases a number of great mitigations that cover basically every possible issue.
The only issue that I don't think is covered here is that collecting all this data up and sending it all at once can sometimes be slow or even time out, and there's no mechanism really to allow GraphQL to defer the collection of some fields until they're ready. It's coming very soon (in the form of @defer; to the spec, to graphql-js, to Relay, and to others) but it's not quite here yet.
The article assumes simple schemas as well - a parent with many child relationships in this article could lead to some complex resolvers. Unless I misunderstand the article many of the strategies here are in ORMs (e.g. lazy subselects) which often don't perform as well as a crafted query given the still multiple roundtrip's to the db. They also require more code, and exhibit branching which means that performance is a function of the users query. If you know your user that's fine, but then again I don't see the advantage vs a straight REST or RPC call which would result in simpler code anyhow. It seems to work IMO in cases I guess when service isn't critical, your model/schema is simple, or you prefer flexibility of data access over reliability/predictability.
How so? There are existing tools that prevent both N+1 problems (Dataloader) and complex, recursive queries (depth and complexity limits).
If your GraphQL schema requires expensive queries because it has a different schema than your database, is it really decoupled?