Home  >  Article  >  Backend Development  >  An in-depth analysis of the GraphQL type system

An in-depth analysis of the GraphQL type system

青灯夜游
青灯夜游forward
2023-02-09 20:21:043652browse

An in-depth analysis of the GraphQL type system

Originally developed at Facebook in 2012 as a better data ingestion solution for underpowered mobile devices, GraphQL was open sourced in 2015. As an API technology designed for flexibility, GraphQL is a powerful enabler for developers and consumers of APIs, as well as the organizations behind them. All details and functionality of the GraphQL implementation are listed in GraphQL Schema. In order to write a valid GraphQL schema, you must understand the GraphQL type system.

In this article, you will learn about GraphQL types: five built-in scalar (scalar) types, enumerations (enums), lists (list) and non-null wrapper (non-null) types, object (object) types, and the abstract interfaces and union types (union) that work with them .

Scalar Types

All data in a GraphQL schema is ultimately parsed into various scalar types, representing primitive values. A GraphQL response can be thought of as a tree, with scalar types being the leaves at the end of the tree. There can be multiple levels in a nested response, but the last level will always resolve to a scalar (or enumeration) type. GraphQL comes with five built-in scalar types: Int, Float, String, Boolean, and ID.

#Int

Int is a signed 32 non-decimal value, it is a signed value that does not include decimals (positive or negative) integer. The maximum value of a signed 32-digit integer is 2,147,483,647. This is one of two built-in scalars for numeric data.

Float

Float is a signed double-precision decimal value. It is a signed (positive or negative) number with a decimal point, such as 1.2, which is another built-in scalar used for numeric data.

String

String is a sequence of UTF-8 characters. The String type is used for any text data, this can also include data such as very large numbers. Most custom scalars are string data types.

Boolean

Boolean contains true and false.

ID

ID is a unique identifier and always serializes as a string, even if ID is a number . ID Types can often be represented by universally unique identifiers (UUIDs).

Custom scalar

In addition to the above built-in scalars, you can also use the scalar keyword to define custom scalars. You can use custom scalars to create types with additional server-level validation, such as Date, Time, or Url. Here's an example of defining a new Date type:

scalar Date

The server will know how to handle interactions with this new type using GraphQLScalarType.

Enumeration (Enum) type

Enum type, also called Enumerator type, is used to describe an Set of possible values.

For example you could create an enumeration for your game character's Job and Species that contains all the values ​​that the system will accept.

"角色的工作等级"
enum Job {
  FIGHTER
  WIZARD
}

"性格的种类或血统"
enum Species {
  HUMAN
  ELF
  DWARF
}

By defining an enumeration type you can ensure that a role's Job can only be FIGHTER or WIZARD, and will never accidentally become something else Some random strings, if you use the String type instead of Enum, they may be other random strings.

Enumerations can also be used as acceptable values ​​in parameters. For example, you could make a Hand enumeration to represent whether the weapon is one-handed (like a short sword) or two-handed (like a heavy axe), and use that to determine whether one or both can be equipped:

enum Hand {  SINGLE
  DOUBLE}"战士使用的一种武器"type Weapon {
  name: String!
  attack: Int
  range: Int
  hand: Hand
}

type Query {
  weapons(hand: Hand = SINGLE): [Weapon]
}

Hand The enumeration has been declared with SINGLE and DOUBLE as values, and the parameters on the weapons fields have default values SINGLE, which means if no parameters are passed, it will default back to SINGLE.

非空类型

可能会注意到内置标量列表中缺少 nullundefined(一种被许多语言视为原始类型的常见类型)。 Null 在 GraphQL 中确实存在,表示缺少一个值。默认情况下,GraphQL 中的所有类型都可以为 null,因此 null 是对任何类型的有效响应。为了使值成为必需值,必须将其转换为带有尾随感叹号的 GraphQL 非空类型。 Non-Null 被定义为类型修饰符,这些类型用于修饰它所引用的类型。例如,String 是一个可选的(或可为空的)字符串,而 String! 是必需的(或非空的)字符串。

列表类型

GraphQL 中的 List 类型是另一种类型修饰符。任何用方括号 ([]) 括起来的类型都会成为 List 类型,这是一个定义列表中每个项目类型的集合,像 JavaScript 中的数组。

例如,定义为 [Int] 的类型意味着这个集合所有元素的类型为 Int 类型,[String] 将是 String 类型的集合。 Non-NullList 可以一起使用,使一个类型既需要又定义为 List,例如 [String]!

对象类型

如果 GraphQL 标量类型描述分层 GraphQL 响应末尾的“叶子”,那么对象类型描述中间的 分支,并且 GraphQL 模式中的几乎所有内容都是一种对象类型。

对象由命名字段(键)列表和每个字段将解析为的值类型组成。对象是用 type 关键字定义的。至少要定义一个或多个字段,字段不能以两个下划线(__)开头,以免与GraphQL自省系统冲突。

例如创建一个 Fighter 对象来表示游戏中的一种角色:

"具有直接战斗能力和力量的英雄"
type Fighter {
  id: ID!
  name: String!
  level: Int
  active: Boolean!
}

在此示例中,声明了 Fighter 对象类型,定义了 4 个字段:

  • id:非空 ID 类型。
  • name:非空字符串类型。
  • levelInt 类型。
  • active:非空布尔类型。

在声明上方,可以使用双引号添加注释,如本例:具有直接战斗能力和力量的英雄,这将显示为类型的描述。

在此示例中,每个字段都解析为标量类型,但对象字段也可以解析为其他对象类型。例如,可以创建一个 Weapon 类型,并且可以设置 GraphQL 模式,其中 Fighter 上的 weapon 字段将解析为一个 Weapon 对象:

"战士使用的一种武器"
type Weapon {
  name: String!
  attack: Int
  range: Int
}

"具有直接战斗能力和力量的英雄"
type Fighter {
  id: ID!
  name: String!
  level: Int
  active: Boolean!
  weapon: Weapon
}

对象也可以嵌套到其他对象的字段中。

根操作类型

有三种特殊对象作为 GraphQL schema 的入口点:QueryMutationSubcription。这些被称为根操作类型,并遵循与任何其他对象类型相同的规则。

schema 关键字表示 GraphQL 模式的入口点。根 QueryMutationSubcription 类型将位于根模式对象上:

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

Query 类型在任何 GraphQL 模式上都是必需的,代表一个读取请求,类似于 REST API GET。以下是返回 Fighter 类型列表的根查询对象的示例:

type Query {
  fighters: [Fighter]
}

Mutations 代表写入请求,类似于 REST API 中的 POSTPUTDELETE。在以下示例中,Mutation 有一个带有命名参数(输入)的 addFighter 字段:

type Mutation {
  addFighter(input: FighterInput): Fighter
}

最后,一个 Subscription 对应于一个事件流,它将与 Web 应用程序中的 Websocket 结合使用。如下所示:

type Subscription {
  randomBattle(enemy: Enemy): BattleResult
}

请注意,schema 入口点通常在某些 GraphQL 实现中被抽象掉。

字段参数

GraphQL 对象的字段本质上是返回值的函数,并且它们可以像任何函数一样接受参数。字段参数由参数名称后跟类型定义,参数可以是任何非对象类型。在此示例中,可以通过 id 字段(解析为非空 ID 类型)过滤 Fighter 对象:

type Query {
  fighter(id: ID!): Fighter
}

这个特定示例对于从数据存储中获取单个项目很有用,但参数也可用于过滤、分页和其他更具体的查询。

接口类型

Object 类型一样,抽象接口类型由一系列命名字段及其关联的值类型组成。接口看起来像并遵循与对象相同的所有规则,但用于定义对象实现的子集。

到目前为止,在 schema 中有一个 Fighter 对象,但可能还想创建一个Wizard、一个 Healer 和其他对象,它们将共享大部分相同的字段但还是存在一些差异。在这种情况下,可以使用接口来定义它们共有的字段,并创建作为接口实现的对象。

在下面的示例中,使用 interface 关键字创建 BaseCharacter 接口,其中包含每种类型的字符将拥有的所有字段:

"A hero on a quest."interface BaseCharacter {
  id: ID!
  name: String!
  level: Int!
  species: Species
  job: Job
}

每个角色类型都有字段 idnamelevelspeciesjob

现在,假设有一个具有这些共享字段的 Fighter 类型和一个 Wizard 类型,但是 Fighters 使用 WeaponWizards 使用 Spells。可以使用 implements 关键字将每个描述为 BaseCharacter 实现,这意味着它们必须具有创建的接口中的所有字段:

type Fighter implements BaseCharacter {
  id: ID!
  name: String!
  level: Int!
  species: Species
  job: Job!
  weapon: Weapon
}
type Wizard implements BaseCharacter {
  id: ID!
  name: String!
  level: Int!
  species: Species
  job: Job!
  spells: [Spell]
}

FighterWizard 都是 BaseCharacter 接口的有效实现,因为它们具有所需的字段子集。

Union 类型

可以与对象一起使用的另一种抽象类型是 union 类型。使用 union 关键字,可以定义一个类型,其中包含所有有效响应的对象列表。

使用上面创建的接口,可以创建一个 Character union,将 character 定义为 WizardFighter

union Character = Wizard | Fighter

等号 = 设置定义,管道符 | 用作 OR 语句。请注意,union 必须由对象或接口组成,标量类型在 union 上无效。

现在,如果查询 characters 列表,它可以使用 Character union 并返回所有 WizardFighter 类型。

总结

上面学习了定义 GraphQL 类型系统的类型,包括最基本的类型是标量类型由 IntFloatStringBooleanID和 GraphQL 实现创建的任何自定义标量类型组成。枚举是有效常量值的列表,当需要对查询响应进行更多控制时,可以使用枚举,而不是简单地将其声明为字符串。列表类型和非空类型被称为类型修饰符 type modifier 或包装类型 wrapping type,它们分别可以将其他类型定义为集合类型或必需类型。GraphQL schema 中的几乎所有内容都是对象类型,包括 querymutationsubscription 入口点。接口和联合类型是抽象类型,在定义对象时很有用。

【相关推荐:Go视频教程编程教学

The above is the detailed content of An in-depth analysis of the GraphQL type system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete