Relay plugin
The Relay plugin adds a number of builder methods and helper functions to simplify building a relay compatible schema.
Usage
Install
Setup
Options
The relay
options object passed to builder can contain the following properties:
idFieldName
: The name of the field that contains the global id for the node. Defaults toid
.idFieldOptions
: Options to pass to the id field.clientMutationId
:omit
(default) |required
|optional
. Determines if clientMutationId fields are created onrelayMutationFields
, and if they are required.cursorType
:String
|ID
. Determines type used for cursor fields. Defaults toString
nodeQueryOptions
: Options for thenode
field on the query object, set to false to omit the fieldnodesQueryOptions
: Options for thenodes
field on the query object, set to false to omit the fieldnodeTypeOptions
: Options for theNode
interface typepageInfoTypeOptions
: Options for theTypeInfo
object typeclientMutationIdFieldOptions
: Options for theclientMutationId
field on connection objectsclientMutationIdInputOptions
: Options for theclientMutationId
input field on connections fieldsmutationInputArgOptions
: Options for the Input object created for each connection fieldcursorFieldOptions
: Options for thecursor
field on an edge object.nodeFieldOptions
: Options for thenode
field on an edge object.edgesFieldOptions
: Options for theedges
field on a connection object.pageInfoFieldOptions
: Options for thepageInfo
field on a connection object.hasNextPageFieldOptions
: Options for thehasNextPage
field on thePageInfo
object.hasPreviousPageFieldOptions
: Options for thehasPreviousPage
field on thePageInfo
object.startCursorFieldOptions
: Options for thestartCursor
field on thePageInfo
object.endCursorFieldOptions
: Options for theendCursor
field on thePageInfo
object.beforeArgOptions
: Options for thebefore
arg on a connection field.afterArgOptions
: Options for theafter
arg on a connection field.firstArgOptions
: Options for thefirst
arg on a connection field.lastArgOptions
: Options for thelast
arg on a connection field.defaultConnectionTypeOptions
: Default options for theConnection
Object types.defaultEdgeTypeOptions
: Default options for theEdge
Object types.defaultPayloadTypeOptions
: Default options for thePayload
Object types.defaultMutationInputTypeOptions
: default options for the mutationInput
types.nodesOnConnection
: If true, thenodes
field will be added to theConnection
object types.defaultConnectionFieldOptions
: Default options for connection fields defined with t.connectionbrandLoadedObjects
: Defaults totrue
. This will add a hidden symbol to objects returned from theload
methods of Nodes that allows the defaultresolveType
implementation to identify the type of the node. When this is enabled, you will not need to implement anisTypeOf
check for most common patterns.
Creating Nodes
To create objects that extend the Node
interface, you can use the new builder.node
method.
builder.node
will create an object type that implements the Node
interface. It will also create
the Node
interface the first time it is used. The resolve
function for id
should return a
number or string, which will be converted to a globalID. The relay plugin adds to new query fields
node
and nodes
which can be used to directly fetch nodes using global IDs by calling the
provided loadOne
or loadMany
method. Each node will only be loaded once by id, and cached if the
same node is loaded multiple times inn the same request. You can provide loadWithoutCache
or
loadManyWithoutCache
instead if caching is not desired, or you are already using a caching
datasource like a dataloader.
Nodes may also implement an isTypeOf
method which can be used to resolve the correct type for
lists of generic nodes. When using a class as the type parameter, the isTypeOf
method defaults to
using an instanceof
check, and falls back to checking the constructor property on the prototype.
The means that for many cases if you are using classes in your type parameters, and all your values
are instances of those classes, you won't need to implement an isTypeOf
method, but it is usually
better to explicitly define that behavior.
By default (unless brandLoadedObjects
is set to false
) any nodes loaded through one of the
load*
methods will be branded so that the default resolveType
method can identify the GraphQL
type for the loaded object. This means isTypeOf
is only required for union
and interface
fields that return node objects that are manually loaded, where the union or interface does not have
a custom resolveType
method that knows how to resolve the node type.
parsing node ids
By default all node ids are parsed as string. This behavior can be customized by providing a custom parse function for your node's ID field:
Global IDs
To make it easier to create globally unique ids the relay plugin adds new methods for creating globalID fields.
The returned IDs can either be a string (which is expected to already be a globalID), or an object
with the an id
and a type
, The type can be either the name of a name as a string, or any object
that can be used in a type parameter.
There are also new methods for adding globalIDs in arguments or fields of input types:
globalIDs used in arguments expect the client to send a globalID string, but will automatically be
converted to an object with 2 properties (id
and typename
) before they are passed to your
resolver in the arguments object.
Limiting global ID args to specific types
globalID
input's can be configured to validate the type of the globalID. This is useful if you
only want to accept IDs for specific node types.
Creating Connections
The t.connection
field builder method can be used to define connections. This method will
automatically create the Connection
and Edge
objects used by the connection, and add before
,
after
, first
, and last
arguments. The first time this method is used, it will also create the
PageInfo
type.
Manually implementing connections can be cumbersome, so there are a couple of helper methods that can make resolving connections a little easier.
For limit/offset based apis:
resolveOffsetConnection
has a few default limits to prevent unintentionally allowing too many
records to be fetched at once. These limits can be configure using the following options:
For APIs where you have the full array available you can use resolveArrayConnection
, which works
just like resolveOffsetConnection
and accepts the same options.
Cursor based pagination can be implemented using the resolveCursorConnection
method. The following
example uses prisma, but a similar solution should work with any data store that supports limits,
ordering, and filtering.
Relay Mutations
You can use the relayMutationField
method to define relay compliant mutation fields. This method
will generate a mutation field, an input object with a clientMutationId
field, and an output
object with the corresponding clientMutationId
.
Example ussage:
Which produces the following graphql types:
The relayMutationField
has 4 arguments:
name
: Name of the mutation fieldinputOptions
: Options for theinput
object or a ref to an existing input objectfieldOptions
: Options for the mutation fieldpayloadOptions
: Options for the Payload object
The inputOptions
has a couple of non-standard options:
name
which can be used to set the name of the input objectargName
which can be used to overwrite the default arguments name (input
).
The payloadOptions
object also accepts a name
property for setting the name of the payload
object.
You can also access refs for the created input and payload objects so you can re-use them in other fields:
Reusing connection objects
In some cases you may want to create a connection object type that is shared by multiple fields. To do this, you will need to create the connection object separately and then create a fields using a ref to your connection object:
builder.connectionObject
creates the connect object type and the associated Edge type.
t.arg.connectionArgs()
will create the default connection args.
Reusing edge objects
Similarly you can directly create and re-use edge objects
builder.connectionObject
creates the connect object type and the associated Edge type.
t.arg.connectionArgs()
will create the default connection args.
Expose nodes
The t.node
and t.nodes
methods can be used to add additional node fields. the expected return
values of id
and ids
fields is the same as the resolve value of t.globalID
, and can either be
a globalID or an object with and an id
and a type
.
Loading nodes by id
uses a request cache, so the same node will only be loaded once per request,
even if it is used multiple times across the schema.
decoding and encoding global ids
The relay plugin exports decodeGlobalID
and encodeGlobalID
as helper methods for interacting
with global IDs directly. If you accept a global ID as an argument you can use the decodeGlobalID
function to decode it:
Using custom encoding for global ids
In some cases you may want to encode global ids differently than the build in ID encoding. To do this, you can pass a custom encoding and decoding function into the relay options of the builder:
Using custom resolve for node and or nodes field
If you need to customize how nodes are loaded for the node
and or nodes
fields you can provide
custom resolve functions in the builder options for these fields:
Extending all connections
There are 2 builder methods for adding fields to all connection objects: t.globalConnectionField
and t.globalConnectionFields
. These methods work like many of the other methods on the builder for
adding fields to objects or interfaces.
In the above example, we are just returning a static number for our totalCount
field. To make this
more useful, we need to have our resolvers for each connection actually return an object that
contains a totalCount for us. To guarantee that resolvers correctly implement this behavior, we can
define custom properties that must be returned from connection resolvers when we set up our builder:
Now typescript will ensure that objects returned from each connection resolver include a totalCount property, which we can use in our connection fields:
Note that adding additional required properties will make it harder to use the provided connection helpers since they will not automatically return your custom properties. You will need to manually add in any custom props after getting the result from the helpers:
Changing nullability of edges and nodes
If you want to change the nullability of the edges
field on a Connection
or the node
field on
an Edge
you can configure this in 2 ways:
Globally
The types provided for DefaultEdgesNullability
and DefaultNodeNullability
must match the values
provided in the nullable option of edgesFieldOptions
and nodeFieldOptions
respectively. This
will set the default nullability for all connections created by your builder.
nullability for edges
fields defaults to { list: options.defaultFieldNullability, items: true }
and the nullability of node
fields is the same as options.defaultFieldNullability
(which
defaults to true
).
Per connection
Extending the Node
interface
Use the nodeInterfaceRef
method of your Builder.
For example, to add a new derived field on the interface: