/lib/graphql-connection
Contents
This optional module creates Relay-style connection types and the opaque cursors they expose.
Functions
createConnectionType
Creates a connection object type for a GraphQL object type.
Parameters
createConnectionType() takes two positional arguments:
| Name | Type | Description |
|---|---|---|
|
|
Generator used to create the schema’s related types. |
|
|
|
GraphQL object type |
Type returned in each connection edge. |
Returns
A GraphQL object type named <TypeName>Connection with these fields:
-
totalCount -
Total number of available items.
-
edges -
List containing each
nodeand its encodedcursor. -
pageInfo -
startCursor,endCursor, andhasNextfor the current page.
The resolver for a field of this type must return a ConnectionSource.
Example
The connection type is created from an existing object type, then used as the type of a field that returns a page of results. The resolver maps the query result onto the three ConnectionSource properties.
PersonConnection and pages through results with it:
const graphQlLib = require('/lib/graphql');
const connectionLib = require('/lib/graphql-connection');
const peopleLib = require('/lib/people');
const personConnectionType = connectionLib.createConnectionType(schemaGenerator, personType);
const rootQueryType = schemaGenerator.createObjectType({
name: 'Query',
fields: {
people: {
type: personConnectionType,
args: {
start: graphQlLib.GraphQLInt,
count: graphQlLib.GraphQLInt
},
resolve: (env) => {
const result = peopleLib.find({
start: env.args.start,
count: env.args.count
});
return {
total: result.total,
start: env.args.start,
hits: result.hits
};
}
}
}
});
encodeCursor
Converts value to a string and returns its Base64 encoding. The encoding is opaque to GraphQL clients, but it is not encryption and must not contain secrets.
Parameters
| Name | Type | Description |
|---|---|---|
|
|
any |
Value to encode. Converted with |
Returns
string — Base64-encoded cursor.
Example
Types created by createConnectionType() encode their own cursors. Call encodeCursor() directly only when building a connection-shaped type by hand.
const cursor = connectionLib.encodeCursor(20);
const expected = 'MjA=';
decodeCursor
Decodes a Base64 cursor.
Parameters
| Name | Type | Description |
|---|---|---|
|
|
any |
Cursor to decode. Converted with |
Returns
string — decoded cursor value.
Example
The decoded value is always a string, so parse it before using it as a number.
const value = connectionLib.decodeCursor('MjA=');
const start = parseInt(value, 10);
const expected = '20';
Type Definitions
ConnectionSource
The value a resolver must return for a field whose type was created by createConnectionType().
| Name | Type | Description |
|---|---|---|
|
|
number |
Total number of available items. |
|
|
number |
Zero-based index of the first item in |
|
|
object[] |
Items in the current page. |