4

The good practice for relations in GraphQL is using the connection model with edge and node elements. The recommendation is also for both edge and node to be nullable. This is how e.g. graphene-sqlalchemy, that I use will map the SQL relations.

My question is: why? As far as my APIs that serve relational data from SQL database go I can't see any situation in which an edge or a node would be null. Thus, if I use statically-typed language on the frontend (like Typescript or Elm) I find myself writing a boilerplate that handles situations which will never occur.

How should I understand these nulls in terms of abstract data model? “There is nothing connected” for me would translate as a connection with no edges. Why do I need a null edge? The null node bothers me even more “There is a connection, but there is nothing on the other end”? Please explain to me the rationale here.

zefciu
  • 1,967
  • 2
  • 17
  • 39

1 Answers1

7

Using connections lines your schema up with the Relay specification -- whether this is good practice when not using Relay is debatable.

In Relay, the edges and nodes are nullable because that's what the spec implicitly specifies.

The practical reason for this is because of the way GraphQL errors work. When an execution error is encountered while resolving a field, that field will resolve to null. However, if the field is also non-null, it can't actually resolve to null and so GraphQL will make the entire parent field null instead. If the parent field is also non-null, then it will make its parent null... and so on. GraphQL errors will "bubble up" this way until either a nullable field is encountered or the data root field is reached (which is always nullable).

In other words, by making the field and edge nullable, we allow the node to error out while resolving while still returning information about the edge itself, and, more importantly, still returning all the other edges. If both nodes and edges were non-null, an error inside a single node would cause the edges field itself to resolve to null. By making these fields nullable, we effectively enable support for GraphQL to return a partial response even if it encounters errors during execution.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183