https://www.yuque.com/books/share/ec8980d3-bf8c-4277-a96d-957455adf289?#(密码:xume) 《GraphQL 教程》
GraphQL 介绍
- GraphQL 是 Facebook 开发的一种用于 API 的数据查询语言并于 2015 年开源
- GraphQL 既是一种用于 API 的查询语言,也是一个满足你数据查询的运行时。
- GraphQL 是一种接口开发标准,支持常见的服务端开发语言。例如:Java、PHP、Python、Node.js 等
- 官方网站:https://graphql.org/
- 中文文档:https://graphql.cn/
- GitHub:https://github.com/graphql
- 未来技术趋势,可能替代 RESTful,但是近几年还不太行
- 因为 RESTful 沉淀了很多年
- 一个新项目可以全部使用 GraphQL
- GraphQL 和 RESTful 结合使用
参考链接
- https://zhuanlan.zhihu.com/p/33876142
- dataloader
- https://github.com/graphql/graphiql
- 5个用/不用GraphQL的理由
- https://github.com/mrdulin/blog/issues/88
GraphQL 入门
GraphQL 相关支持
查看:https://graphql.org/code/。
- 后端
- 客户端
- 工具
- 服务
GraphQL.js
GraphQL.js 是一个 GraphQL 的参考实现。
为了处理 GraphQL 查询,我们需要定义一个 Query 类型的 schema。我们还需要一个 API 根节点,为每个 API 端点提供一个名为 resolver 的函数。对于只返回 Hello world! 的 API,我们可以将此代码放在名为 server.js 的文件中:
const { graphql, buildSchema } = require('graphql')
// 1. 使用 GraphQL schema 语法构建一个 schema
const schema = buildSchema(`
type Query {
hello: String
}
`)
// 2. 根节点为每个 API 入口端点提供一个 resolver 函数
const root = {
hello: () => {
return 'Hello world!'
}
}
// 3. 运行 GraphQL query '{ hello }' ,输出响应
graphql(schema, '{ hello }', root).then(response => {
console.log(response) // 输出结果:{ data: { hello: 'Hello world!' } }
})
Express GraphQL
在实际应用中,你可能不会在命令行工具里执行 GraphQL,而是会想从一个 API 服务器运行 GraphQL 查询。比如 Node.js Express。
1、安装依赖
npm install express express-graphql graphql
2、示例代码
const { buildSchema } = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const cors = require('cors')
const app = express()
// 允许客户端跨域请求
app.use(cors())
// 1. 使用 GraphQL schema 语法构建一个 schema
const schema = buildSchema(`
type Query {
foo: String
count: Int
}
`)
// 2. 定义 scheme 的 resolver
const rootValue = {
foo () {
return 'bar'
},
count () {
return 123
}
}
// 3. 挂载 GraphQL 中间件
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true // 开启浏览器 GraphQL IDE 调试工具
}))
// 4. 启动 Web 服务
app.listen(4000, () => {
console.log('GraphQL Server is running at http://localhost:4000/')
})
// 3. 查询
// graphql(schema, '{ count, foo }', root).then(res => {
// console.log(res)
// })
总结:
- 服务端通过定义的数据类型规定了可以提供的各种形式的数据
- 类型的字段要有对应的 resolver 提供对应的解析
- 客户端可以根据服务端定义的数据类型选择性查询需要的字段信息
GraphQL 客户端
在有了 express-graphql 的情况下,你可以向 GraphQL 服务器上的入口端点发送一个 HTTP POST 请求,其中将 GraphQL 查询作为 JSON 载荷的 query 字段,就能调用 GraphQL 服务器。
JavaScript 请求查询示例如下:
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: '{ foo, count }'
}
}).then(res => {
console.log(res)
})
GraphQL 浏览器测试工具
- 开启方式
- 基本使用
- 编写
- 验证
- 测试
- 键盘快捷键
- 格式化查询:Shift-Ctrl-P
- 合并查询:Shift-Ctrl-M
- 执行查询:Ctrl-Enter
- 自动完成:Ctrl-Space
- 查询文档
GraphQL 模式和类型
Query 类型
- 严格来说是一种对象类型
- 是所有查询的入口点
- 必须有,并且不能重复
标量类型
所谓的标量类型也就是基本类型。
- Int:有符号 32 位整数。
- Float:有符号双精度浮点值。
- String:UTF‐8 字符序列。
- Boolean:true 或者 false。
- ID:ID 标量类型表示一个唯一标识符,通常用以重新获取对象或者作为缓存中的键。ID 类型使用和 String 一样的方式序列化;然而将其定义为 ID 意味着并不需要人类可读性。
对象类型
- 花括号中是对象的字段信息
- 属性名称是自定义的
- 属性名后面的类型为 GraphQL 内置的标量类型
- GraphQL 使用 # 注释
列表类型
# 这表示数组本身可以为空,但是其不能有任何空值成员。
myField: [String!]
# 不可为空的字符串数组
myField: [String]!
# 数组本身不能为空,其中的数据也不能为空
myField: [String!]!
非空类型
- 默认情况下,每个类型都是可以为空的,意味着所有的标量类型都可以返回 null
- 使用感叹号可以标记一个类型不可为空,如 String! 表示非空字符串
- 如果是列表类型,使用方括号将对应类型包起来,如 [Int] 就表示一个整数列表。
枚举类型
也称作枚举(enum),枚举类型是一种特殊的标量,它限制在一个特殊的可选值集合内。这让你能够:
- 验证这个类型的任何参数是可选值的的某一个
- 与类型系统沟通,一个字段总是一个有限值集合的其中一个值。
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
#这表示无论我们在 schema 的哪处使用了 Episode,都可以肯定它返回的是 NEWHOPE、EMPIRE 和 JEDI 之一。
Mutation 类型
- 是修改的入口点
Input 类型
- 参数对象必须使用 Input 定义
服务器端示例:
/**
* schema 类型:
* - 参数
* - 修改
* - 输入类型
*/
const { buildSchema } = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const cors = require('cors')
const { v4: uuidv4 } = require('uuid')
const app = express()
app.use(cors())
const articles = [
{ id: '1', title: 'article 1', body: 'article 1 body' },
{ id: '2', title: 'article 2', body: 'article 2 body' },
{ id: '3', title: 'article 3', body: 'article 3 body' }
]
const schema = buildSchema(`
type Article {
id: ID!
title: String!
body: String!
tagList: [String!]
}
# 查询的入口点
type Query {
articles: [Article]
article(id: ID!): Article
}
# 参数对象必须使用 Input 定义
input CreateArticleInput {
title: String!
body: String!
tagList: [String!]
}
input UpdateArticleInput {
title: String!
body: String!
}
type DeletionStatus {
success: Boolean!
}
# 修改入口点
type Mutation {
createArticle(article: CreateArticleInput): Article
updateArticle(id: ID!, article: UpdateArticleInput): Article
deleteArticle(id: ID!): DeletionStatus
}
`)
const rootValue = {
articles () {
return articles
},
article ({ id }) {
return articles.find(article => article.id === id)
},
createArticle ({ article }) {
article.id = uuidv4()
articles.push(article)
return article
},
updateArticle ({ id, article: postArticle }) {
const article = articles.find(article => article.id === id)
article.title = postArticle.title
article.body = postArticle.body
return article
},
deleteArticle ({ id }) {
const index = articles.find(article => article.id === id)
articles.splice(index, 1)
return {
success: true
}
}
}
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true
}))
app.listen(4000, () => {
console.log('GraphQL Server is running at http://localhost:4000/')
})
客户端示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./node_modules/axios/dist/axios.js"></script>
<script>
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
mutation deleteArteicle($id: ID!) {
deleteArticle(id: $id) {
success
}
}
`,
variables: {
id: 2
}
}
}).then(res => {
console.log(res.data)
})
// 更新文章
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
mutation updateArteicle($id: ID!, $article: UpdateArticleInput) {
updateArticle(id: $id, article: $article) {
id
title
body
}
}
`,
variables: {
id: 2,
article: {
title: 'aaa',
body: 'bbb'
}
}
}
}).then(res => {
console.log(res.data)
})
// 创建文章
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
mutation createArteicle($article: CreateArticleInput) {
createArticle(article: $article) {
id
title
body
}
}
`,
variables: {
article: {
title: 'aaa',
body: 'bbb'
}
}
}
}).then(res => {
console.log(res.data)
})
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
query getArticles($id: ID!) {
article(id: $id) {
id
title
}
}
`,
variables: {
id: 2
}
}
}).then(res => {
console.log(res.data)
})
// 获取单个文章
const id = 1
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
query getArticles {
article(id: ${id}) {
id
title
}
}
`
}
}).then(res => {
console.log(res.data)
})
// 获取文章列表
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
query getArticles {
articles {
title
}
}
`
}
}).then(res => {
console.log(res.data)
})
</script>
</body>
</html>