/lib/graphql
Contents
The main module defines GraphQL types, assembles them into a schema, and executes operations against that schema.
Constants
The module exports scalar type objects that can be assigned directly to a field or argument’s type property.
| Export | Description |
|---|---|
|
|
Signed 32-bit integer. |
|
|
Double-precision floating-point value. |
|
|
UTF-8 character sequence. |
|
|
|
|
|
Identifier serialized as a string. |
|
|
Arbitrary JSON-compatible value. |
|
|
ISO-8601 calendar date. |
|
|
ISO-8601 time with an offset. |
|
|
ISO-8601 date and time with an offset. |
|
|
ISO-8601 date and time without a time-zone offset. |
|
|
ISO-8601 time without a time-zone offset. |
Functions
newSchemaGenerator
Creates an independent SchemaGenerator. Use the same generator for the related types and the schema, because it also collects resolver registrations.
Returns
SchemaGenerator — functions for constructing GraphQL types and a schema.
Example
Create the generator once per schema, in the module that builds it.
const graphQlLib = require('/lib/graphql');
const schemaGenerator = graphQlLib.newSchemaGenerator();
list
Wraps a type as a GraphQL list. The list and its items remain nullable unless separately wrapped with nonNull().
Parameters
| Name | Type | Description |
|---|---|---|
|
|
GraphQL type |
Type of each list item. |
Returns
GraphQL list type.
Example
const tagsField = {
type: graphQlLib.list(graphQlLib.GraphQLString),
resolve: (env) => env.source.tags
};
nonNull
Wraps a type as non-null.
Parameters
| Name | Type | Description |
|---|---|---|
|
|
GraphQL type |
Type that must not resolve to |
Returns
GraphQL non-null type.
Example
nonNull() and list() apply to whatever they wrap, so wrapping in both directions makes the list itself mandatory as well as each of its items.
const requiredString = graphQlLib.nonNull(graphQlLib.GraphQLString);
const requiredStrings = graphQlLib.nonNull(
graphQlLib.list(graphQlLib.nonNull(graphQlLib.GraphQLString))
);
reference
Creates a type reference by name. References allow self-referencing or mutually dependent types to be declared before the referenced concrete type exists.
Parameters
| Name | Type | Description |
|---|---|---|
|
|
string |
Exact GraphQL name of the referenced type. |
Returns
GraphQL type reference.
Example
The name must match the referenced type exactly, and that type must be reachable from the schema or listed in the schema’s dictionary.
const personReference = graphQlLib.reference('Person');
execute
Executes a GraphQL operation against a schema. The arguments are positional.
Parameters
| Name | Type | Description |
|---|---|---|
|
|
GraphQL schema |
Schema created with |
|
|
string |
GraphQL query, mutation, or subscription document. |
|
|
object |
Optional. Values for variables declared by the operation. |
|
|
any |
Optional. Application-specific value exposed to resolvers as |
Returns
ExecutionResult — query and mutation results contain data and, when applicable, errors. For a subscription, data is a publisher whose subscribe() method accepts a subscriber from /lib/graphql-rx.
Example
A universal API that accepts a query and its variables in the request body, and passes a context value that every resolver can read as env.context.
exports.POST = (req) => {
const body = JSON.parse(req.body);
const result = graphQlLib.execute(schema, body.query, body.variables, {
request: req
});
return {
contentType: 'application/json',
body: JSON.stringify(result)
};
};
const expected = {
data: {
person: {
name: 'James'
}
}
};
Classes
SchemaGenerator
A schema generator creates GraphQL types and assembles them into a schema. Each generator is independent and accumulates the resolvers for the types it creates, so the types belonging to one schema must all come from the same generator. Except for createPageInfoObjectType(), each type-creation method creates a new named GraphQL type.
The generator has no constructor. All the examples below use one created with newSchemaGenerator():
const graphQlLib = require('/lib/graphql');
const schemaGenerator = graphQlLib.newSchemaGenerator();
createSchema
Assembles the schema from its root types.
Parameters
createSchema() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
GraphQL object type |
Root query type. Every schema requires one. |
|
|
GraphQL object type |
Optional. Root mutation type. |
|
|
GraphQL object type |
Optional. Root subscription type. |
|
|
GraphQL object type[] |
Optional. Additional concrete types that are not otherwise reachable when the schema is assembled, including types addressed only through |
Returns
GraphQL schema.
Example
Types reached only through reference() are listed in dictionary, because the generator cannot find them by walking the root types.
const schema = schemaGenerator.createSchema({
query: rootQueryType,
mutation: rootMutationType,
dictionary: [personType]
});
createObjectType
Creates an object type.
Parameters
createObjectType() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
string |
Unique GraphQL type name. |
|
|
object |
Map of field names to OutputField definitions. |
|
|
GraphQL interface type[] |
Optional. Interfaces implemented by the object. Entries may be concrete interface types or type references. |
|
|
string |
Optional. Description exposed through GraphQL introspection. |
Returns
GraphQL object type.
Example
A field without a resolve function reads the property of the same name from the source, so name needs none. The children field refers to Person by name, because the type is not assigned to a variable until the call returns.
Throughout these examples /lib/people stands for the application’s own data module. The library places no requirements on where a resolver gets its values.
Person type over the application’s own data:
const peopleLib = require('/lib/people');
const personType = schemaGenerator.createObjectType({
name: 'Person',
description: 'A person.',
fields: {
name: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
},
age: {
type: graphQlLib.GraphQLInt
},
children: {
type: graphQlLib.list(graphQlLib.reference('Person')),
resolve: (env) => peopleLib.getChildren(env.source.name)
}
}
});
createPageInfoObjectType
Creates the cached page-info object type used by /lib/graphql-connection. The first invocation on a schema generator creates the type; later invocations return that same type. Application code normally uses createConnectionType() instead of calling this directly.
Its params properties and return value are the same as createObjectType().
Example
Because the type is cached per generator, calling this twice on the same generator yields the same type rather than a duplicate-name error.
const pageInfoType = schemaGenerator.createPageInfoObjectType({
name: 'PageInfo',
fields: {
startCursor: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
},
endCursor: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
},
hasNext: {
type: graphQlLib.nonNull(graphQlLib.GraphQLBoolean)
}
}
});
createInputObjectType
Creates an input object type for use in field arguments.
Parameters
createInputObjectType() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
string |
Unique GraphQL input type name. |
|
|
object |
Map of field names to InputField definitions. |
|
|
string |
Optional. Description exposed through GraphQL introspection. |
Returns
GraphQL input object type.
Example
Input types group related arguments. Assign the created type to an entry in a field’s args, and read it from env.args in the resolver.
const personFilterType = schemaGenerator.createInputObjectType({
name: 'PersonFilter',
fields: {
namePrefix: {
type: graphQlLib.GraphQLString
},
count: {
type: graphQlLib.GraphQLInt
}
}
});
const rootQueryType = schemaGenerator.createObjectType({
name: 'Query',
fields: {
people: {
type: graphQlLib.list(personType),
args: {
filter: personFilterType
},
resolve: (env) => peopleLib.find({
namePrefix: env.args.filter.namePrefix,
count: env.args.filter.count
}).hits
}
}
});
createInterfaceType
Creates an interface type.
Parameters
createInterfaceType() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
string |
Unique GraphQL interface name. |
|
|
object |
Map of field names to InterfaceField definitions. |
|
|
function |
Receives the source value and returns the concrete GraphQL object type for that value. |
|
|
string |
Optional. Description exposed through GraphQL introspection. |
Returns
GraphQL interface type.
Example
An object type declares the interfaces it implements through its own interfaces property. Every type the typeResolver can return must be reachable from the schema or listed in the schema’s dictionary.
const partyType = schemaGenerator.createInterfaceType({
name: 'Party',
fields: {
name: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
}
},
typeResolver: (party) => party.orgNumber ? organizationType : personType
});
const organizationType = schemaGenerator.createObjectType({
name: 'Organization',
interfaces: [partyType],
fields: {
name: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
},
orgNumber: {
type: graphQlLib.nonNull(graphQlLib.GraphQLString)
}
}
});
createUnionType
Creates a union type.
Parameters
createUnionType() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
string |
Unique GraphQL union name. |
|
|
GraphQL object type[] |
Non-empty array of possible concrete types. Entries may be object types or type references. |
|
|
function |
Receives the source value and returns its concrete GraphQL object type. |
|
|
string |
Optional. Description exposed through GraphQL introspection. |
Returns
GraphQL union type.
Example
A union combines unrelated types without requiring them to share any fields, so clients select fields per type with inline fragments.
const searchResultType = schemaGenerator.createUnionType({
name: 'SearchResult',
types: [personType, organizationType],
typeResolver: (hit) => hit.orgNumber ? organizationType : personType
});
createEnumType
Creates an enum type.
Parameters
createEnumType() takes a single params object with these properties:
| Name | Type | Description |
|---|---|---|
|
|
string |
Unique GraphQL enum name. |
|
|
string[] or object |
Enum names as an array, or an object mapping GraphQL enum names to their runtime values. |
|
|
string |
Optional. Description exposed through GraphQL introspection. |
Returns
GraphQL enum type.
Example
Passing an array uses each name as its own value. Passing an object keeps the GraphQL names uppercase while resolvers receive the mapped value.
const sortDirectionType = schemaGenerator.createEnumType({
name: 'SortDirection',
values: ['ASC', 'DESC']
});
const priorityType = schemaGenerator.createEnumType({
name: 'Priority',
values: {
LOW: 1,
NORMAL: 2,
HIGH: 3
}
});
Type Definitions
OutputField
Defines a field on an object type.
| Name | Type | Description |
|---|---|---|
|
|
GraphQL output type |
Field result type. |
|
|
object |
Optional. Map of argument names to GraphQL input types. |
|
|
function or value |
Optional. Resolver invoked with a ResolverEnvironment, or a fixed value. When omitted, GraphQL reads a property with the field’s name from |
InterfaceField
Defines a field on an interface.
| Name | Type | Description |
|---|---|---|
|
|
GraphQL output type |
Field result type. |
|
|
object |
Optional. Map of argument names to GraphQL input types. |
InputField
Defines a field on an input object.
| Name | Type | Description |
|---|---|---|
|
|
GraphQL input type |
Input field type. |
ResolverEnvironment
The object passed to an output-field resolver.
| Name | Type | Description |
|---|---|---|
|
|
any |
Value returned by the parent field. |
|
|
object |
Arguments supplied for the current field. |
|
|
any |
Context passed to |
ExecutionResult
The mapped result returned by execute() and delivered to subscription callbacks.
| Name | Type | Description |
|---|---|---|
|
|
object or publisher |
Resolved operation data. A subscription returns a publisher instead of an object. |
|
|
object[] |
Optional. Validation or data-fetching errors. Each error includes |