graphql/type
Thegraphql/type module is responsible for defining GraphQL types and schema. You can import either from thegraphql/type module, or from the rootgraphql module. For example:
import { GraphQLSchema }from 'graphql';Overview
Schema
Definitions
class GraphQLScalarTypeA scalar type within GraphQL.class GraphQLObjectTypeAn object type within GraphQL that containsfields.class GraphQLInterfaceTypeAn interface type within GraphQL that definesfields implementations will contain.class GraphQLUnionTypeA union type within GraphQL that defines a listof implementations.class GraphQLEnumTypeAn enum type within GraphQL that defines a list ofvalid values.class GraphQLInputObjectTypeAn input object type within GraphQL thatrepresents structured inputs.class GraphQLListA type wrapper around other types that represents alist of those types.class GraphQLNonNullA type wrapper around other types that represents anon-null version of those types.
Predicates
function isInputTypeReturns if a type can be used as input types forarguments and directives.function isOutputTypeReturns if a type can be used as output types asthe result of fields.function isLeafTypeReturns if a type can be a leaf value in a response.function isCompositeTypeReturns if a type can be the parent context ofa selection set.function isAbstractTypeReturns if a type is a combination of objecttypes.
Un-modifiers
function getNullableTypeStrips any non-null wrappers from a type.function getNamedTypeStrips any non-null or list wrappers from a type.
Scalars
const GraphQLIntA scalar type representing integers.const GraphQLFloatA scalar type representing floats.const GraphQLStringA scalar type representing strings.const GraphQLBooleanA scalar type representing booleans.const GraphQLIDA scalar type representing IDs.
Schema
GraphQLSchema
class GraphQLSchema { constructor(config: GraphQLSchemaConfig);}type GraphQLSchemaConfig = { query: GraphQLObjectType; mutation?: GraphQLObjectType;};A Schema is created by supplying the root types of each type of operation,query and mutation (optional). A schema definition is then supplied to thevalidator and executor.
Example
const MyAppSchema = new GraphQLSchema({ query: MyAppQueryRootType, mutation: MyAppMutationRootType,});Definitions
GraphQLScalarType
class GraphQLScalarType<InternalType,ExternalType> { constructor(config: GraphQLScalarTypeConfig<InternalType,ExternalType>);}type GraphQLScalarTypeConfig<InternalType,ExternalType>= { name: string; description?: string; specifiedByURL?: Maybe<string>; serialize: (outputValue: unknown)=> ExternalType; parseValue?: (inputValue: unknown)=> InternalType; parseLiteral?: ( valueAST: Value, variables?: Maybe<Record<string,unknown>>, )=> InternalType;};The leaf values of any request and input values to arguments areScalars (or Enums) and are defined with a name and a series of serializationfunctions used to ensure validity.
Example
const OddType = new GraphQLScalarType({ name:'Odd', // Can be used to link to a specification // for this scalar, for instance the JSON // specification. specifiedByURL:'', description: 'This custom scalar will only return a value if the passed in value is an odd integer, when it's not it will return null.' serialize: (outputValue) =>{ // This function gets called for response-data, the application returns data // for a property and in the schema we see that this value has the "Odd" type. returntypeof outputValue=== 'number' && outputValue% 2 === 1 ? value: null; }, parseValue: (inputValue)=> { // This function gets called for input-data, i.e. variables being passed in return typeof inputValue=== 'number' && outputValue% 2 === 1 ? value: null; }, parseLiteral(ast) { // This function gets called when the value is passed in as a literal on the // Executable GraphQL Document if (ast.kind === Kind.INT) { return oddValue(parseInt(ast.value,10)); } return null; },});GraphQLObjectType
class GraphQLObjectType { constructor(config: GraphQLObjectTypeConfig);}type GraphQLObjectTypeConfig = { name: string; interfaces?: GraphQLInterfacesThunk | GraphQLInterfaceType[]; fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap; isTypeOf?: (value: any,info?: GraphQLResolveInfo)=> boolean; description?: string;};type GraphQLInterfacesThunk = ()=> Array<GraphQLInterfaceType>;type GraphQLFieldConfigMapThunk = ()=> GraphQLFieldConfigMap;// See below about resolver functions.type GraphQLFieldResolveFn = ( source?: any, args?: { [argName: string]: any }, context?: any, info?: GraphQLResolveInfo,)=> any;type GraphQLResolveInfo = { fieldName: string; fieldNodes: Array<Field>; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; schema: GraphQLSchema; fragments: { [fragmentName: string]: FragmentDefinition }; rootValue: any; operation: OperationDefinition; variableValues: { [variableName: string]: any };};type GraphQLFieldConfig = { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; resolve?: GraphQLFieldResolveFn; deprecationReason?: string; description?: string;};type GraphQLFieldConfigArgumentMap = { [argName: string]: GraphQLArgumentConfig;};type GraphQLArgumentConfig = { type: GraphQLInputType; defaultValue?: any; description?: string;};type GraphQLFieldConfigMap = { [fieldName: string]: GraphQLFieldConfig;};Almost all of the GraphQL types you define will be object types. Object typeshave a name, but most importantly describe their fields.
When two types need to refer to each other, or a type needs to refer toitself in a field, you can use a function expression (aka a closure or athunk) to supply the fields lazily.
Note that resolver functions are provided thesource object as the first parameter.However, if a resolver function is not provided, then the default resolver isused, which looks for a method onsource of the same name as the field. If found,the method is called with(args, context, info). Since it is a method onsource,that value can always be referenced withthis.
Examples
const AddressType = new GraphQLObjectType({ name:'Address', fields: { street: { type: GraphQLString }, number: { type: GraphQLInt }, formatted: { type: GraphQLString, resolve(obj) { return obj.number+ ' ' + obj.street; }, }, },});const PersonType = new GraphQLObjectType({ name:'Person', fields: ()=> ({ name: { type: GraphQLString }, bestFriend: { type: PersonType }, }),});GraphQLInterfaceType
class GraphQLInterfaceType { constructor(config: GraphQLInterfaceTypeConfig);}type GraphQLInterfaceTypeConfig = { name: string; fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap; resolveType?: (value: any,info?: GraphQLResolveInfo)=> GraphQLObjectType; description?: string;};When a field can return one of a heterogeneous set of types, a Interface typeis used to describe what types are possible, what fields are in common acrossall types, as well as a function to determine which type is actually usedwhen the field is resolved.
Example
const EntityType = new GraphQLInterfaceType({ name:'Entity', fields: { name: { type: GraphQLString }, },});GraphQLUnionType
class GraphQLUnionType { constructor(config: GraphQLUnionTypeConfig);}type GraphQLUnionTypeConfig = { name: string; types: GraphQLObjectsThunk | GraphQLObjectType[]; resolveType?: (value: any,info?: GraphQLResolveInfo)=> GraphQLObjectType; description?: string;};type GraphQLObjectsThunk = ()=> GraphQLObjectType[];When a field can return one of a heterogeneous set of types, a Union typeis used to describe what types are possible as well as providing a functionto determine which type is actually used when the field is resolved.
Example
const PetType = new GraphQLUnionType({ name:'Pet', types: [DogType, CatType], resolveType(value) { if (valueinstanceof Dog) { return DogType; } if (valueinstanceof Cat) { return CatType; } },});GraphQLEnumType
class GraphQLEnumType { constructor(config: GraphQLEnumTypeConfig);}type GraphQLEnumTypeConfig = { name: string; values: GraphQLEnumValueConfigMap; description?: string;};type GraphQLEnumValueConfigMap = { [valueName: string]: GraphQLEnumValueConfig;};type GraphQLEnumValueConfig = { value?: any; deprecationReason?: string; description?: string;};type GraphQLEnumValueDefinition = { name: string; value?: any; deprecationReason?: string; description?: string;};Some leaf values of requests and input values are Enums. GraphQL serializesEnum values as strings, however internally Enums can be represented by anykind of type, often integers.
Note: If a value is not provided in a definition, the name of the enum valuewill be used as its internal value.
Example
const RGBType = new GraphQLEnumType({ name:'RGB', values: { RED: { value:0 }, GREEN: { value:1 }, BLUE: { value:2 }, },});GraphQLInputObjectType
class GraphQLInputObjectType { constructor(config: GraphQLInputObjectConfig);}type GraphQLInputObjectConfig = { name: string; fields: | GraphQLInputObjectConfigFieldMapThunk | GraphQLInputObjectConfigFieldMap; description?: string;};type GraphQLInputObjectConfigFieldMapThunk = ()=> GraphQLInputObjectConfigFieldMap;type GraphQLInputObjectFieldConfig = { type: GraphQLInputType; defaultValue?: any; description?: string;};type GraphQLInputObjectConfigFieldMap = { [fieldName: string]: GraphQLInputObjectFieldConfig;};type GraphQLInputObjectField = { name: string; type: GraphQLInputType; defaultValue?: any; description?: string;};type GraphQLInputObjectFieldMap = { [fieldName: string]: GraphQLInputObjectField;};An input object defines a structured collection of fields which may besupplied to a field argument.
UsingNonNull will ensure that a value must be provided by the query
Example
const GeoPoint = new GraphQLInputObjectType({ name:'GeoPoint', fields: { lat: { type:new GraphQLNonNull(GraphQLFloat) }, lon: { type:new GraphQLNonNull(GraphQLFloat) }, alt: { type: GraphQLFloat, defaultValue:0 }, },});GraphQLList
class GraphQLList { constructor(type: GraphQLType);}A list is a kind of type marker, a wrapping type which points to anothertype. Lists are often created within the context of defining the fields ofan object type.
Example
const PersonType = new GraphQLObjectType({ name:'Person', fields: ()=> ({ parents: { type:new GraphQLList(PersonType) }, children: { type:new GraphQLList(PersonType) }, }),});GraphQLNonNull
class GraphQLNonNull { constructor(type: GraphQLType);}A non-null is a kind of type marker, a wrapping type which points to anothertype. Non-null types enforce that their values are never null and can ensurean error is raised if this ever occurs during a request. It is useful forfields which you can make a strong guarantee on non-nullability, for exampleusually the id field of a database row will never be null.
Example
const RowType = new GraphQLObjectType({ name:'Row', fields: ()=> ({ id: { type:new GraphQLNonNull(String) }, }),});Predicates
isInputType
function isInputType(type: GraphQLType): booleanThese types may be used as input types for arguments and directives.
isOutputType
function isOutputType(type: GraphQLType): boolean;These types may be used as output types as the result of fields
isLeafType
function isLeafType(type: GraphQLType): boolean;These types may describe types which may be leaf values
isCompositeType
function isCompositeType(type: GraphQLType): boolean;These types may describe the parent context of a selection set
isAbstractType
function isAbstractType(type: GraphQLType): boolean;These types may describe a combination of object types
Un-modifiers
getNullableType
function getNullableType(type: GraphQLType): GraphQLNullableType;If a given type is non-nullable, this strips the non-nullability andreturns the underlying type.
getNamedType
function getNamedType(type: GraphQLType): GraphQLNamedType;If a given type is non-nullable or a list, this repeated strips thenon-nullability and list wrappers and returns the underlying type.
Scalars
GraphQLInt
let GraphQLInt: GraphQLScalarType;AGraphQLScalarType that represents an int.
GraphQLFloat
let GraphQLFloat: GraphQLScalarType;AGraphQLScalarType that represents a float.
GraphQLString
let GraphQLString: GraphQLScalarType;AGraphQLScalarType that represents a string.
GraphQLBoolean
let GraphQLBoolean: GraphQLScalarType;AGraphQLScalarType that represents a boolean.
GraphQLID
let GraphQLID: GraphQLScalarType;AGraphQLScalarType that represents an ID.