I just started experimenting with graphene-django/GraphQL and am pretty confused about the relay library that has been brought in for graphene-django. After running through the cookbook example (implementing it with my own models) and running a test query, upon POST the query gets transformed to a strangely nested object with edges and nodes. What are these and what are they doing?
{
companies {
edges {
node {
id
}
}
}
}
Node
It may be worth mentioning that
Nodeis part of the Facebook Relay specs (not GraphQL specs). However, most framework (Graphene included) implement this spec due to the close association between Relay and GraphQL.Essentially
Nodeis an interface that implements just anIDfield, which is meant to be an globally unique identifier for an object.IDs are designed to be opaque (typical convention is tobase64('type:id')), applications should not attempt to rely on this implementation detail.Nodeis exposed as part of the root Query, where applications can query for entities with knownIDin a convenient way, e.g. refetching, fetching fields that have not been fetched.This provides the convenience of not having to define query point for every model you expose (e.g.
message(messageId)oruser(userId)). This also allows you to query for the object without transversing through an object path, exampleConnection
Like
Node,Connectionis also part of the Relay specs that made its way to mainstream adoption.At first glance, the concept of
edgesseems superfluous but it does solve some tricky use case. Consider the need to expose a many-to-many relationship like 'friends', typically implemented in a database with a join table.It is now easy to display "Friends since [date here]" by exposing
friends.created_atin the edge object.edgesessentially defines the relationship betweennodes.