Relay is a Javascript framework built by Facebook with the purpose of improving the GraphQL architecture by making some core assumptions:
Basically speaking, it gives every object a global unique identifier, creates a cursor-based pagination structure and introduces the input parameter to mutations.
You can read more about the GraphQL server side considerations in the GraphQL Relay Specification and in the Graphene Documentation.
Graphene and Graphene Django already comes with the Relay implementation, making your life easier.
You are going to recreate a little part of the application. Some code will be duplicated, but it’s just for learning purposes. On production systems I recommend you to use Relay whenever possible.
First of all, let’s implement our link query using Relay. You will write all the following code in a new schema file, keeping things separated. The nomenclature used across the code – prefixed with Relay – is used to avoid confusion and it’s not needed on real world scenarios.
Let’s go over the essential changes:
#1
: Relay allows you to use django-filter for filtering data. Here, you’ve defined a FilterSet, with the url
and description
fields.#2
: The data is exposed in Nodes, so you must create one for the links.#3
: Each node implements an interface with an unique ID (you’ll see the result of this in a bit).#4
: Uses the LinkNode
with the relay_link
field inside your new query.#5
: Defines the relay_links
field as a Connection, which implements the pagination structure.In Insomnia, try out the Relay query:
Some differences from the last queries:
What about the pagination? Each field has some arguments for controlling it: before
, after,
first
and last
. On top of that, each edge has a pageInfo
object, including the cursor for navigating between pages.
The first: 1
parameter limits the response for the first result. You also requested the pageInfo
, which returned the navigation cursors.
With first: 1, after:"YXJyYXljb25uZWN0aW9uOjA="
the response returned is the first one after the last link.
Defining mutations with Relay is pretty straightforward.
The changes here are mostly on classes and methods names. You can now create links!
The variation here is the input
argument, which accepts the defined url
and description
arguments as a dictionary.