Back to home

GraphQL 简明教程

Source: https://www.safaribooksonline.com/library/view/learning-graphql/

设计 Schema

类型

  • 标量 Int, Float, String, Boolean, ID
  • 枚举 enum PhotoCategory { SELFIE PORTRAIT ACTION LANDSCAPE GRAPHIC }

关系和列表

[String] 定义了一个字符串列表。

  • [Int] 一个可为 null 的整形列表。
  • [Int!] 一个不可为 null 的整形列表。
  • [Int]! 一个不可为 null 的整形列表,内容可以为 null。
  • [Int!]! 一个元素以及列表都不可为 null 的整形列表。

一对一关系: “type User { githubLogin: ID! name: String avatar: String }

type Photo { id: ID! name: String! url: String! description: String created: DateTime! category: PhotoCategory! postedBy: User! }”

一对多关系:

type User { githubLogin: ID! name: String avatar: String postedPhotos: [Photo!]! }

多对多关系:

type User { friends: [User!]! }

或者将关系独立出来,如果你需要更多属性来描述关系:

type User { friends: [Friendship!]! } type Friendship { friend_a: User! friend_b: User! howLong: Int! whereWeMet: Location }

不同类型列表:

  • 联合类型:

query schedule { agenda { ...on Workout { name reps } ...on StudyGroup { name subject students } } }

  • 接口:将多个类型定义的同名同类型字段抽象为接口。

query schedule { agenda { name start end ...on Workout { reps } } }

参数

query { allPhotos(category: "SELFIE") { name description url } }

分页:

type Query { ... allUsers(first: Int=50 start: Int=0): [User!]! allPhotos(first: Int=25 start: Int=0): [Photo!]! }

排序:

query { allPhotos(sortBy: name) }

变更

通过加上一个类型为 Mutation 的字段,比如命名为 mutation

schema { query: Query mutation: Mutation }

然后通过如下语句去提交一个新的记录:

mutation { postPhoto(name: "Sending the Palisades") { id url created postedBy { name } } }

输入类型

因为变更引入的参数很多,我们可以定义一个专有输入类型:

“input PostPhotoInput { name: String! description: String category: PhotoCategory=PORTRAIT }

type Mutation { postPhoto(input: PostPhotoInput!): Photo! }”

然后调用时直接引用该类型:

mutation newPhoto($input: PostPhotoInput!) { postPhoto(input: $input) { id url created } }

返回

自定义返回格式

“type AuthPayload { user: User! token: String! }

type Mutation { … githubAuth(code: String!): AuthPayload! }”

订阅

在类型中申明支持订阅的字段:

“type Subscription { newPhoto: Photo! newUser: User! }

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

订阅支持过滤,比如只关心 “ACTION” 累心的照片:

subscription { newPhoto(category: "ACTION") { id name url postedBy { name } } }

Schema 文档

类型申明时记得添加注释:

“# A user who has been authorized by GitHub at least once type User {

# The user's unique GitHub login
githubLogin: ID!

# The user's first and last name
name: String

# A url to the user's GitHub profile photo
avatar: String

# All of the photos posted by this user
postedPhotos: [Photo!]!

# All of the photos in which this user appears
inPhotos: [Photo!]!

}”