Search code examples
graphqlhotchocolate

Does HotChocolate GraphQL server lead to tight coupling between the API and the database?


I'm trying to wrap my head around GraphQL in general and a HotChocolate demo I just watched. Here's what I see as benefits:

  • Client can request any combination of fields thus offering maximum flexibility
  • Queries are directly translated into SQL resulting in high performance and little overhead

My question or concern, if you want so, is: doesn't this couple my API to the database at a level that's almost certain to break at some point? If I need to adjust my DB schema, things will break. Is this concern valid?


Solution

  • Hot Chocolate or GraphQL in general are only meant to be a tiny wrapper on top of your existing APIs.

    What's shown as a resolver in the demo

    [UseProjection]
    // ...
    public IQueryable<Entity> GetEntities(DbContext context) => context.Entities;
    

    could just as well be a tiny wrapper on top of existing services, such as a repository for example.

    public List<Entity> GetEntities([Service] IService service)
        => service.GetEntities();
    

    The Data middleware shown in the linked demo exists to allow people to get started with as little boilerplate and as efficient as possible, but it inherently conflicts with what GraphQL is supposed to be.

    It's ultimately a trade-off each developer has to decide for himself. With Hot Chocolate the Data middleware is really powerful, but it introduces coupling and also has its limitations. On the other hand you gain the ability to move fast(er), be efficient and avoid much of the boilerplate that would usually be required.

    Of course you are free to choose the more traditional route as well, with more boilerplate, but decoupled. In this scenario GraphQL just acts as a thin API layer, as it was intended.

    I think this is the beauty of GraphQL, that you have this choice and the ability to wire up almost any data source or service behind a GraphQL server.

    About your concern of Database migrations breaking the data middleware. It is valid, but most of the time Hot Chocolate is really smart about picking up new fields and wiring them up correctly, without you having to write any additional code.