GiraphQL
Search…
Relay
The Relay plugin adds a number of builder methods a helper functions to simplify building a relay compatible schema.

Usage

Install

1
yarn add @giraphql/plugin-relay
Copied!

Setup

1
import RelayPlugin from '@giraphql/plugin-relay';
2
const builder = new SchemaBuilder({
3
plugins: [RelayPlugin],
4
relayOptions: {
5
clientMutationId: 'omit',
6
cursorType: 'String',
7
},
8
});
Copied!

Options

The relayOptions object passed to builder can contain the following properties:
    clientMutationId: required (default) | omit | optional. Determins if clientMutationId
    fields are created on connections, and if they are required.
    cursorType: String | ID. Determines type used for cursor fields. Defaults behavior due to
    legacy reasons is String for everything except for connection arguments which use ID.
    Overwritting this default is hightly encouraged.
    nodeQueryOptions: Options for the node field on the query object
    nodesQueryOptions: Options for the nodes field on the query object
    nodeTypeOptions: Options for the Node interface type
    pageInfoTypeOptions: Options for the TypeInfo object type
    clientMutationIdFieldOptions: Options for the clientMutationId field on connection objects
    clientMutationIdInputOptions: Options for the clientMutationId input field on connections
    fields
    mutationInputArgOptions: Options for the Input object created for each connection field
    cursorFieldOptions: Options for the cursor field on an edge object.
    nodeFieldOptions: Options for the node field on an edge object.
    edgesFieldOptions: Options for the edges field on a connection object.
    pageInfoFieldOptions: Options for the pageInfo field on a connection object.
    hasNextPageFieldOptions: Options for the hasNextPage field on the PageInfo object.
    hasPreviousPageFieldOptions: Options for the hasPreviousPage field on the PageInfo object.
    startCursorFieldOptions: Options for the startCursor field on the PageInfo object.
    endCursorFieldOptions: Options for the endCursor field on the PageInfo object.
    beforeArgOptions: Options for the before arg on a connection field.
    afterArgOptions: Options for the after arg on a connection field.
    firstArgOptions: Options for the first arg on a connection field.
    lastArgOptions: Options for the last arg on a connection field.

Global IDs

To make it easier to create globally unique ids the relay plugin adds new methods for creating globalID fields.
1
import { encodeGlobalID } from '@giraphql/plugin-relay';
2
3
builder.queryFields((t) => ({
4
singleID: t.globalID({
5
resolve: (parent, args, context) => {
6
return encodeGlobalID('SomeType', 123);
7
},
8
}),
9
listOfIDs: t.globalIDList({
10
resolve: (parent, args, context) => {
11
return [{ id: 123, type: 'SomeType' }];
12
},
13
}),
14
}));
Copied!
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:
1
builder.queryType({
2
fields: (t) => ({
3
fieldThatAcceptsGlobalID: t.boolean({
4
args: {
5
id: t.arg.globalID({
6
required: true,
7
}),
8
idList: t.arg.globalIDList(),
9
},
10
resolve(parent, args) {
11
console.log(`Get request for type ${args.id.type} with id ${args.id.typename}`);
12
return true;
13
},
14
}),
15
}),
16
});
Copied!
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.

Creating Nodes

To create objects that extend the Node interface, you can use the new builder.node method.
1
class NumberThing {
2
id: number;
3
4
binary: string;
5
6
constructor(n: number) {
7
this.id = n;
8
this.binary = n.toString(2);
9
}
10
}
11
12
builder.node(NumberThing, {
13
id: {
14
resolve: (num) => num.id,
15
// other options for id field can be added here
16
},
17
loadOne: (id) => new NumberThing(parseInt(id)),
18
loadMany: (ids) => ids.map((id) => new NumberThing(parseInt(id))),
19
name: 'Number',
20
fields: (t) => ({
21
binary: t.exposeString('binary', {}),
22
}),
23
});
Copied!
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 loadOne and loadMany methods are optional, and loadMany will be used if both are present. These methods allow a nodes to be loaded by id. The relay plugin adds to new query fields node and nodes which can be used to directly fetch nodes using global IDs.
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 ussually better to explicitly define that behavior.

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.
1
builder.queryFields((t) => ({
2
numbers: t.connection(
3
{
4
type: NumberThing,
5
resolve: (parent, { first, last, before, after }) => {
6
return resolveOffsetConnection({ args }, ({ limit, offset }) => {
7
return {
8
pageInfo: {
9
hasNextPage: false,
10
hasPreviousPage: false,
11
startCursor: 'abc',
12
endCursor: 'def',
13
},
14
edges: [
15
{
16
cursor: 'xyz',
17
node: new NumberThing(123),
18
},
19
],
20
};
21
});
22
},
23
},
24
{
25
name: 'NameOfConnectionType', // optional, will use ParentObject + capitalize(FieldName) + "Connection" as the default
26
fields: (tc) => ({
27
// define extra fields on Connection
28
// We need to use a new variable for the connection field builder (eg tc) to get the correct types
29
}),
30
// Other options for connection object can be added here
31
},
32
{
33
// Same as above, but for the Edge Object
34
name: 'NameOfEdgeType', // optional, will use Connection name + "Edge" as the default
35
fields: (te) => ({
36
// define extra fields on Edge
37
// We need to use a new variable for the connection field builder (eg te) to get the correct types
38
}),
39
},
40
),
41
}));
Copied!
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:
1
import { resolveOffsetConnection } from '@giraphql/plugin-relay';
2
3
builder.queryFields((t) => ({
4
numbers: t.connection({
5
type: SomeThings,
6
resolve: (parent, args) => {
7
return resolveOffsetConnection({ args }, ({ limit, offset }) => {
8
return getThings(offset, limit);
9
});
10
},
11
}),
12
}));
Copied!
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:
1
{
2
args: ConnectionArguments;
3
defaultSize?: number; // defaults to 20
4
maxSize?: number; // defaults to 100
5
}
Copied!
For APIs where you have the full array available you can use resolveArrayConnection, which works just like resolveOffsetConnection and accepts the same options.
1
import { resolveArrayConnection } from '@giraphql/plugin-relay';
2
3
builder.queryFields((t) => ({
4
numbers: t.connection({
5
type: SomeThings,
6
resolve: (parent, args) => {
7
return resolveOffsetConnection({ args }, getAllTheThingsAsArray());
8
},
9
}),
10
}));
Copied!
I am planning to add more helpers in the future.

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:
1
builder.relayMutationField(
2
'deleteItem',
3
{
4
inputFields: (t) => ({
5
id: t.id({
6
required: true,
7
}),
8
}),
9
},
10
{
11
resolve: async (root, args, ctx) => {
12
if (ctx.items.has(args.input.id)) {
13
ctx.items.delete(args.input.id);
14
15
return { success: true };
16
}
17
18
return { sucess: false };
19
},
20
},
21
{
22
outputFields: (t) => ({
23
sucess: t.boolean({
24
resolve: (result) => result.success,
25
}),
26
}),
27
},
28
);
Copied!
Which produces the following graphql types:
1
input DeleteItemInput {
2
clientMutationId: ID!
3
id: ID!
4
}
5
6
type DeleteItemPayload {
7
clientMutationId: ID!
8
itWorked: Boolean!
9
}
10
11
type Mutation {
12
deleteItem(input: DeleteItemInput!): DeleteItemPayload!
13
}
Copied!
The relayMutationField has 4 arguments:
    name: Name of the mutation field
    inputOptions: Options for the input object
    fieldOptions: Options for the mutation field
    payloadOptions: 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 object
    argName 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:
1
// Using aliases when destructuring lets you name your refs rather than using the generic `inputType` and `payloadType`
2
const { inputType: DeleteItemInput, payloadType: DeleteItemPayload } = builder.relayMutationField(
3
'deleteItem',
4
...
5
);
Copied!

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:
1
import { resolveOffsetConnection } from '@giraphql/plugin-relay';
2
3
const ThingsConnection = builder.connectionObject(
4
{
5
// connection optionss
6
type: SomeThing,
7
name: 'ThingsConnection',
8
},
9
{
10
// Edge options (optional)
11
name: 'ThingsEdge', // defaults to Appending `Edge` to the Connection name
12
},
13
);
14
15
builder.queryFields((t) => ({
16
things: t.connection({
17
type: ThingsConnection,
18
args: {
19
...t.arg.connectionArgs(),
20
},
21
resolve: (parent, args) => {
22
return resolveOffsetConnection({ args }, ({ limit, offset }) => {
23
return getThings(offset, limit);
24
});
25
},
26
}),
27
}));
Copied!
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.
1
builder.queryFields((t) => ({
2
extraNode: t.node({
3
id: () => 'TnVtYmVyOjI=',
4
}),
5
moreNodes: t.nodeList({
6
ids: () => ['TnVtYmVyOjI=', { id: 10, type: 'SomeType' }],
7
}),
8
}));
Copied!

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:
1
builder.mutationFields((t) => ({
2
updateThing: t.field({
3
type: Thing,
4
args: {
5
id: t.args.id({ required: true }),
6
update: t.args.string({ required: true }),
7
},
8
resolve(parent, args) {
9
const { type, id } = decodeGlobalId(args.id);
10
11
const thing = Thing.findById(id);
12
13
thing.update(args.update);
14
15
return thing;
16
},
17
}),
18
}));
Copied!

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:
1
import '@giraphql/plugin-relay';
2
const builder = new SchemaBuilder({
3
plugins: ['GiraphQLRelay'],
4
relayOptions: {
5
encodeGlobalID: (typename: string, id: string | number | bigint) => `${typename}:${id}`,
6
decodeGlobalID: (globalID: string) => {
7
const [typename, id] = globalID.split(':');
8
9
return { typename, id };
10
},
11
},
12
});
Copied!

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.
1
builder.globalConnectionField('totalCount', (t) =>
2
t.int({
3
nullable: false,
4
resolve: (parent) => 123,
5
}),
6
);
7
// Or
8
builder.globalConnectionFields((t) => ({
9
totalCount: t.int({
10
nullable: false,
11
resolve: (parent) => 123,
12
}),
13
}));
Copied!
In the above example, we are just returning a static nubmer 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 correclty implement this behavior, we can define custom properties that must be returned from connection resolvers when we set up our builder:
1
import '@giraphql/plugin-relay';
2
const builder = new SchemaBuilder<{
3
Connection: {
4
totalCount: number;
5
};
6
}>({
7
plugins: ['GiraphQLRelay'],
8
relayOptions: {},
9
});
Copied!
Now typescript will ensure that objects returned from each connection resolver include a totalCount property, which we can use in our connection fields:
1
builder.globalConnectionField('totalCount', (t) =>
2
t.int({
3
nullable: false,
4
resolve: (parent) => parent.totalCount,
5
}),
6
);
Copied!
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 gettig the result from the helpers:
1
builder.queryFields((t) => ({
2
posts: t.connection({
3
type: Post,
4
resolve: (parent, args, context) => {
5
const postsArray = context.Posts.getAll();
6
const result = resolveArrayConnection({ args }, postsArray);
7
8
return result && { totalCount: postsArray.length, ...result };
9
},
10
}),
11
}));
Copied!
Last modified 27d ago