GraphQL.JS 文档
graphql/类型

graphql/type

graphql/type 模块负责定义 GraphQL 类型和结构。你可以从 graphql/type 模块或根 graphql 模块导入。例如:

¥The graphql/type module is responsible for defining GraphQL types and schema. You can import either from the graphql/type module, or from the root graphql module. For example:

import { GraphQLSchema } from "graphql" // ES6
var { GraphQLSchema } = require("graphql") // CommonJS

概述

¥Overview

结构

¥Schema

定义

¥Definitions

谓词

¥Predicates

Un-modifiers

标量

¥Scalars

结构

¥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 the validator and executor.

示例

¥Example

var MyAppSchema = new GraphQLSchema({
  query: MyAppQueryRootType,
  mutation: MyAppMutationRootType
});

定义

¥Definitions

GraphQLScalarType

class GraphQLScalarType<InternalType> {
  constructor(config: GraphQLScalarTypeConfig<InternalType>)
}
 
type GraphQLScalarTypeConfig<InternalType> = {
  name: string;
  description?: string;
  serialize: (value: mixed) => InternalType;
  parseValue?: (value: mixed) => InternalType;
  parseLiteral?: (valueAST: Value) => InternalType;
}

任何请求的叶值和参数的输入值都是标量(或枚举),并使用名称和一系列用于确保有效性的序列化函数进行定义。

¥The leaf values of any request and input values to arguments are Scalars (or Enums) and are defined with a name and a series of serialization functions used to ensure validity.

示例

¥Example

var OddType = new GraphQLScalarType({
  name: "Odd",
  serialize: oddValue,
  parseValue: oddValue,
  parseLiteral(ast) {
    if (ast.kind === Kind.INT) {
      return oddValue(parseInt(ast.value, 10))
    }
    return null
  }
})
 
function oddValue(value) {
  return value % 2 === 1 ? value : 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;
};

你定义的几乎所有 GraphQL 类型都是对象类型。对象类型有一个名称,但最重要的是描述它们的字段。

¥Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields.

当两种类型需要相互引用,或者一个类型需要在字段中引用自身时,你可以使用函数表达式(也称为闭包或 thunk)来延迟提供字段。

¥When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

请注意,解析器函数提供 source 对象作为第一个参数。但是,如果未提供解析器函数,则使用默认解析器,该解析器在 source 上查找与字段同名的方法。如果找到,则使用 (args, context, info) 调用该方法。由于它是 source 上的方法,因此该值始终可以用 this 引用。

¥Note that resolver functions are provided the source object as the first parameter. However, if a resolver function is not provided, then the default resolver is used, which looks for a method on source of the same name as the field. If found, the method is called with (args, context, info). Since it is a method on source, that value can always be referenced with this.

示例

¥Examples

var AddressType = new GraphQLObjectType({
  name: "Address",
  fields: {
    street: { type: GraphQLString },
    number: { type: GraphQLInt },
    formatted: {
      type: GraphQLString,
      resolve(obj) {
        return obj.number + " " + obj.street
      }
    }
  }
})
 
var 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 type is used to describe what types are possible, what fields are in common across all types, as well as a function to determine which type is actually used when the field is resolved.

示例

¥Example

var 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 type is used to describe what types are possible as well as providing a function to determine which type is actually used when the field is resolved.

示例

¥Example

var PetType = new GraphQLUnionType({
  name: "Pet",
  types: [DogType, CatType],
  resolveType(value) {
    if (value instanceof Dog) {
      return DogType
    }
    if (value instanceof 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;
}

请求和输入值的一些叶值是枚举。GraphQL 将 Enum 值序列化为字符串,但在内部 Enum 可以用任何类型(通常是整数)表示。

¥Some leaf values of requests and input values are Enums. GraphQL serializes Enum values as strings, however internally Enums can be represented by any kind of type, often integers.

注意:如果定义中未提供值,则枚举值的名称将用作其内部值。

¥Note: If a value is not provided in a definition, the name of the enum value will be used as its internal value.

示例

¥Example

var 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 be supplied to a field argument.

使用 NonNull 将确保查询必须提供一个值

¥Using NonNull will ensure that a value must be provided by the query

示例

¥Example

var 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 another type. Lists are often created within the context of defining the fields of an object type.

示例

¥Example

var PersonType = new GraphQLObjectType({
  name: "Person",
  fields: () => ({
    parents: { type: new GraphQLList(PersonType) },
    children: { type: new GraphQLList(PersonType) },
  }),
})

GraphQLNonNull

class GraphQLNonNull {
  constructor(type: GraphQLType)
}

非空是一种类型标记,是指向另一种类型的封装类型。非空类型强制其值永远不为空,并且可以确保在请求期间发生这种情况时引发错误。它对于可以对非空性做出强有力保证的字段很有用,例如通常数据库行的 id 字段永远不会为空。

¥A non-null is a kind of type marker, a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can make a strong guarantee on non-nullability, for example usually the id field of a database row will never be null.

示例

¥Example

var RowType = new GraphQLObjectType({
  name: "Row",
  fields: () => ({
    id: { type: new GraphQLNonNull(String) },
  }),
})

谓词

¥Predicates

isInputType

function isInputType(type: GraphQLType): boolean

这些类型可以用作参数和指令的输入类型。

¥These 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 and returns the underlying type.

getNamedType

function getNamedType(type: GraphQLType): GraphQLNamedType

如果给定类型不可为空或列表,则此重复将去除不可为空和列表封装器并返回基础类型。

¥If a given type is non-nullable or a list, this repeated strips the non-nullability and list wrappers and returns the underlying type.

标量

¥Scalars

GraphQLInt

let GraphQLInt: GraphQLScalarType

代表 int 的 GraphQLScalarType

¥A GraphQLScalarType that represents an int.

GraphQLFloat

let GraphQLFloat: GraphQLScalarType

代表浮点数的 GraphQLScalarType

¥A GraphQLScalarType that represents a float.

GraphQLString

let GraphQLString: GraphQLScalarType

代表字符串的 GraphQLScalarType

¥A GraphQLScalarType that represents a string.

GraphQLBoolean

let GraphQLBoolean: GraphQLScalarType

代表布尔值的 GraphQLScalarType

¥A GraphQLScalarType that represents a boolean.

GraphQLID

let GraphQLID: GraphQLScalarType

代表 ID 的 GraphQLScalarType

¥A GraphQLScalarType that represents an ID.