In this post, we'll look into the double declaration problem of (GraphQL) APIs in Web Applications.
First I'll define the problem and see that it should actually be called quintuple declaration problem. Once the problem is clear, I'll propose an optimal solution. Who is suffering from the double declaration problem? Essentially, everybody who is writing Web Applications has to deal with the problem. So, if you're a web developer, or you manage web developers, this post is for you! There's also a video accompanying this blog post if you're interested in seeing everything in action: https://youtu.be/ftu8MM5BmGE
Alright, what's the double declaration problem, why is it important and why is the name actually misleading. If you ask Google about for GraphQL double declaration problem you'll get a few good results which explain the issue well. In a nutshell, it describes the problem that as a developer, you have to define the GraphQL Operation (e.g. Query or Mutation) as well as the type definitions for the inputs as well as the response. This is a problem because you have to keep the two in sync. If you add a field to your Query, you also have to add the field to the response structure, e.g. a TypeScript interface. This is not only boring extra work but also error prone because every non-automated task is a good candidate for errors.
Now that we understand the problem, why is "double declaration" misleading?
So far, we've talked about two declarations, the GraphQL Query as well as the type definition of the response. What did we miss? Starting from the backend, we have to define the schema of the database. Next, we have to define the schema of the GraphQL API. Finally, to connect the user interface, we have to build another schema for the UI components / forms. At this point, we've reached a quintuple. We could easily add more layers, e.g. input validation at the backend but this should be enough for now.
So, to recap the complete flow:
- Define the database schema
- Define the API schema
- Write a GraphQL Operation
- Define the response type definition
- Define the UI components / build the forms