Two important things about GraphQL schema design

gvidon
ottofeller
Published in
2 min readJan 16, 2019

GraphQL is a great tool and it is becoming more and more popular. When you start it first time suppress your temptation to start coding. Read this article first. I would also recommend reading this part of Apollo official docs, which gives detailed advices on how to design your GraphQL schema.

Always reuse your types

Don’t create types which are specific to a particular query, and which are basically are subset of some bigger types. This is huge mistake!

Let me show you an example.

Imagine you are developing image hosting website and in order to fetch images you need a query which requests some owner user info along with image data.

Never do like this:

You won’t believe but I saw someone doing this!

This is how your schema and query should look like:

Image hosting GraphQL schema
The query which is based on the schema above

GraphQL is all about nested types!

The core idea is to allow client side developers to fetch exactly those data they need, to let them pick a specific part of a bigger data record based on the need of particular UI/CLI/whatever. Never treat it as REST, which sends tailor-made data structures!

Don’t update nested records within single mutation

Updating nested records can be really tricky on back end side and not less confusing on front end. Thus it’s very important to have add/update mutations which only update single record (in terms of DB record).

If you need to update a relation between records, then stick to the following rule — add/update mutations must only accept two values in nested objects:

  • null in case of removal of a relation
  • and {id} in case of establishing a relation.

Let me show an example again:

File rename and changing the owner were requested in this mutation

As you can see while the mutation above requests all data of an owner, it doesn’t send all owner’s data while updating relation between the image and a user.

Also note that even though file is a nested type, updates for it were still sent in this mutation. It’s ok because file is not nested record, but just a type, without id property and all the data of a file are stored in an image record.

In conclusion

Having a concise list of types which is not growing like a snowball during every week of an app development will be very beneficial in a long term perspective. Apparently these two rules is not a silver bullet aimed to keep your GraphQL workflow in a perfect state but I’m convinced these are must-have rules, the foundation of a clear and simple workflow protocol.

OttoFeller is the software development company specialising in front end of complex web applications and in promising cutting edge technologies.

--

--