Improve your GraphQL schema with Relay Specification

Dzmitry Bayarchyk
ITNEXT
Published in
4 min readSep 24, 2019

--

Apollo and Relay in GraphQL

Do we need to follow Relay Specification even if we don’t use Relay at the client?

Currently, there are 2 major GraphQL clients: Apollo and Relay. Apollo is a very flexible and un opinioned framework that works with any kind of GraphQL schema. Relay is a very opinioned framework by Facebook that requires your server to follow the Relay Specification. So not any kind of GraphQL server is suitable for Relay GraphQL client. That is probably is one of the reasons why Apollo is a preferable choice for most developers.

But why our GraphQL servers don’t support this specification when we don’t work with Relay? Sometimes we may think that we don’t need it because it could seem like overkilling or maybe somebody just doesn’t know about it.

In this article, we will try to understand why this specification is useful, how it helps to avoid breaking changes and even reduce some boilerplate. We will try to go through the basic concepts of the Relay Specification and show why it could be a good choice for your future schema design.

Nodes

So what is a node? Node is a basic building block in Relay specification that has an id. Every entity that has an id needs to implement this interface. But why is it necessary? The idea behind that interface is that every entity that has an id has to be accessible via one single query:

But how is it possible to fetch the required entity based only on id? The ID is usually a random value. What exactly we want to get, is it a post or comment, how do we know what controller to use to fetch the correct data?

The idea is to store the entity type directly in the id before sending the data to the client. Then based on that extended id it will be easy to know what type of entity it is and what controller to choose. If you use javascript in your GraphQL server there is a package with the utils to combine the entity type and actual id. This package is called graphql-relay there you will need toGlobalId and…

--

--