GraphQL 介绍
官网介绍:GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。
传统的 API 调用一般获取到的是后端组装好的一个完整对象,而前端可能只需要用其中的某些字段,大部分数据的查询和传输工作都浪费了。GraphQL 提供一种全新数据查询方式,可以只获取需要的数据,使 API 调用更灵活、高效和低成本。
- 官方网站:graphql.org/
- 中文文档:graphql.cn/
- GitHub:github.com/graphql
GraphQL 入门
GraphQL.js
GraphQL.js 是一个 GraphQL 的参考实现。
- GitHub 仓库:github.com/graphql/gra…
- 使用指南:graphql.org/graphql-js/
为了处理 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 express = require('express')
const { graphqlHTTP } = require('express-graphql')
const { buildSchema } = require('graphql')
// 使用 GraphQL Schema Language 创建一个 schema
const schema = buildSchema(`
type Query {
hello: String
}
`)
// root 提供所有 API 入口端点相应的解析器函数
const root = {
hello: () => {
return 'Hello world!'
}
}
const app = express()
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
})
)
app.listen(4000, () => {
console.log('Running a GraphQL API server at http://localhost:4000/graphql')
})
总结:
- 服务端通过定义的数据类型规定了可以提供的各种形式的数据
- 类型的字段要有对应的 resolver 提供对应的解析
- 客户端可以根据服务端定义的数据类型选择性查询需要的字段信息
GraphQL 客户端
在有了 express-graphql 的情况下,你可以向 GraphQL 服务器上的入口端点发送一个 HTTP POST 请求,其中将 GraphQL 查询作为 JSON 载荷的 query 字段,就能调用 GraphQL 服务器。
JavaScript 请求查询示例如下:
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({query: "{ hello }"})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
传递参数:
var dice = 3;
var sides = 6;
var query = `query RollDice($dice: Int!, $sides: Int) {
rollDice(numDice: $dice, numSides: $sides)
}`;
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: { dice, sides },
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
GraphQL 模式和类型
Query 类型 / Mutation 类型
每一个 GraphQL 服务都有一个 query 类型,可能有一个 mutation 类型。这两个类型和常规对象类型无差,但是它们之所以特殊,是因为它们定义了每一个 GraphQL 查询的入口。
除了作为 schema 的入口,Query 和 Mutation 类型与其它 GraphQL 对象类型别无二致,它们的字段也是一样的工作方式。
- Query 类型是客户端默认的查询类型, Mutation 类型是进行增删改的类型
- Query 类型必须存在
- Query 是唯一的,不能重复定义
服务端:
type Query {}
type Mutation {}
客户端:
# 查询
{}
query {}
query queryName {}
# 增删改
mutation {}
mutation mutationName {}
标量类型
所谓的标量类型也就是基本类型。
GraphQL schema language 支持的标量类型有
Int:有符号 32 位整数。Float:有符号双精度浮点值。String:UTF‐8 字符序列。Boolean:true或者false。ID:ID 标量类型表示一个唯一标识符,通常用以重新获取对象或者作为缓存中的键。ID 类型使用和 String 一样的方式序列化;然而将其定义为 ID 意味着并不需要人类可读性。
类型的作用:
- 约束数据格式,防止出现不合理数据
- 如果数据可以合理的转换为对应的数据类型则不会报错,例如字符串
"123"可以被合理的转换为数字123
这些类型都直接映射 JavaScript,所以你可以直接返回原本包含这些类型的原生 JavaScript 对象。下面是一个展示如何使用这些基本类型的示例:
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// 使用 GraphQL schema language 构建一个 schema
var schema = buildSchema(`
type Query {
quoteOfTheDay: String
random: Float!
rollThreeDice: [Int]
}
`);
// root 将会提供每个 API 入口端点的解析函数
var root = {
quoteOfTheDay: () => {
return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within';
},
random: () => {
return Math.random();
},
rollThreeDice: () => {
return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6));
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
对象类型
一个 GraphQL schema 中的最基本的组件是对象类型,它就表示你可以从服务上获取到什么类型的对象,以及这个对象有什么字段。使用 GraphQL schema language,我们可以这样表示它:
type User {
name: String
age: Int
}
type Query {
user: User
}
列表
# 这表示数组本身可以为空,但是其不能有任何空值成员。
myField: [String!]
# 不可为空的字符串数组
myField: [String]!
# 数组本身不能为空,其中的数据也不能为空
myField: [String!]!
非空
- 默认情况下,每个类型都是可以为空的,意味着所有的标量类型都可以返回
null - 使用感叹号可以标记一个类型不可为空,如
String!表示非空字符串 - 如果是列表类型,使用方括号将对应类型包起来,如
[Int]就表示一个整数列表。
枚举类型
也称作枚举(enum) ,枚举类型是一种特殊的标量,它限制在一个特殊的可选值集合内。这让你能够:
- 验证这个类型的任何参数是可选值的的某一个
- 与类型系统沟通,一个字段总是一个有限值集合的其中一个值。
下面是一个用 GraphQL schema 语言表示的 enum 定义:
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
这表示无论我们在 schema 的哪处使用了 Episode,都可以肯定它返回的是 NEWHOPE、EMPIRE 和 JEDI 之一。
注意,各种语言实现的 GraphQL 服务会有其独特的枚举处理方式。对于将枚举作为一等公民的语言,它的实现就可以利用这个特性;而对于像 JavaScript 这样没有枚举支持的语言,这些枚举值可能就被内部映射成整数值。当然,这些细节都不会泄漏到客户端,客户端会根据字符串名称来操作枚举值。
传递参数
- 传递参数时也要为参数设置类型,并可设置是否为非空参数, 且可以传递多个参数
- 客户端请求带有参数的查询,可以设置默认值
示例:
const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');
// 使用 GraphQL schema language 构造一个 schema
const schema = buildSchema(`
type Query {
userAge(name: String!, sex: String): Int
}
`);
// root 为每个端点入口 API 提供一个解析器
const rootValue = {
userAge: ({name, sex}) => 18
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
客户端请求示例:
const query = `query userAge($name: String!, $sex: String = 'F') {
userAge(name: $name, sex: $sex)
}`;
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: { name: 'lisa', sex: 'M' },
})
})...
Input 类型
有时需要传递一个对象做为参数,例如在创建一个对象时。此时参数的类型需要定义为 input 类型
服务端片段:
type Article {
id: ID!
title: String!
body: String!
tagList: [String!]
}
# 参数对象必须使用 Input 定义
input CreateArticleInput {
title: String!
body: String!
tagList: [String!]
}
# Mutation 入口点
type Mutation {
createArticle(article: CreateArticleInput): Article
}
客户端片段(参数):
{
query: `Mutation CreateArticle($article: CreateArticleInput) {
createArticle(article: $article) {
id
}
}`,
variables: { article: {title:'aaa', body: 'bbb'} }
}
客户端操作示例
获取所有文章列表:
axios({
method: 'POST', // GraphQL 的请求方法必须是 POST
url: 'http://localhost:4000/graphql',
data: {
query: `
query getArticles {
articles {
title
}
}
`
}
}).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)
})
添加文章:
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: `
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 deleteArteicle($id: ID!) {
deleteArticle(id: $id) {
success
}
}
`,
variables: {
id: 2
}
}
}).then(res => {
console.log(res.data)
})
GraphQl 查询其他注意点
别名(Aliases)
当需要传参查询某些数据时,由于字段名称(hero)相同,所以无法传递不同参数来查询数据。此时可以使用别名,避免字段冲突。
{
empireHero: hero(episode: EMPIRE) {
name
}
jediHero: hero(episode: JEDI) {
name
}
}
片段(Fragments)
GraphQL 包含了称作片段的可复用单元。如果我们请求的数据中,两个对象中有多个字段一致,可以使用片段来避免字段重复,且片段中可以使用变量。
query HeroComparison($first: Int = 3) {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}
fragment comparisonFields on Character {
name
friendsConnection(first: $first) {
totalCount
edges {
node {
name
}
}
}
}
片段不能引用其自身或者创造回环,因为这会导致结果无边界。下面查询是无效的:
{
hero {
...NameAndAppearancesAndFriends
}
}
fragment NameAndAppearancesAndFriends on Character {
name
appearsIn
friends {
...NameAndAppearancesAndFriends
}
}
指令(Directives)
有时我们可能需要一个方式使用变量动态地改变我们查询的结构。譬如我们假设有个 UI 组件,其有概括视图和详情视图,后者比前者拥有更多的字段。
query Hero($withFriends: Boolean!) {
hero {
name
friends @include(if: $withFriends) {
name
}
}
}
我们用了 GraphQL 中一种称作指令的新特性。一个指令可以附着在字段或者片段包含的字段上,然后以任何服务端期待的方式来改变查询的执行。GraphQL 的核心规范包含两个指令,其必须被任何规范兼容的 GraphQL 服务器实现所支持:
@include(if: Boolean)仅在参数为true时,包含此字段。@skip(if: Boolean)如果参数为true,跳过此字段。
指令在你不得不通过字符串操作来增减查询的字段时解救你。服务端实现也可以定义新的指令来添加新的特性。
接口(Interfaces)/ 内联片段(Inline Fragments)
接口是一个抽象类型,它包含某些字段,而对象类型必须包含这些字段,才能算实现了这个接口。
定义一个接口 Character。任何实现 Character 的类型都要具有这些字段,并有对应参数和返回类型, 但也可以拥有自己其他的字段
interface Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
}
type Human implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
starships: [Starship]
totalCredits: Int
}
type Droid implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
primaryFunction: String
}
type Query {
hero(id: ID!): Character
}
hero 字段返回 Character 类型,它可能是 Human 类型或者 Droid 类型。所以下边例子中查询 primaryFunction 会报错,因为 Character 中不包含 primaryFunction。
query HeroForId($id: ID!) {
hero(id: $id) {
name
primaryFunction
}
}
如果要查询一个只存在于特定对象类型上的字段,可以使用内联片段:
query HeroForId($id: ID!) {
hero(id: $id) {
name
... on Droid {
primaryFunction
}
... on Human {
starships
}
}
}
联合类型(Union Types)/ 元字段(Meta fields)
联合类型和接口十分相似,但是它并不指定类型之间的任何共同字段。
interface Character {
id: ID!
name: String!
}
type Human implements Character {
id: ID!
name: String!
height: Float
friends: [Character]
}
type Droid implements Character {
id: ID!
name: String
primaryFunction: String
}
type Starship {
name: String
length: Float
}
union SearchResult = Human | Droid | Starship
type Query {
search(text: String!): SearchResult
}
在我们的schema中,任何返回一个 SearchResult 类型的地方(search),都可能得到一个 Human、Droid 或者 Starship。注意,联合类型的成员需要是具体对象类型;你不能使用接口或者其他联合类型来创造一个联合类型。
这时候,如果你需要查询一个返回 SearchResult 联合类型的字段,那么你得使用内联片段才能查询任意字段。
{
search(text: "an") {
__typename
... on Human {
name
height
}
... on Droid {
name
primaryFunction
}
... on Starship {
name
length
}
}
}
某些情况下,你并不知道你将从 GraphQL 服务获得什么类型,这时候你就需要一些方法在客户端来决定如何处理这些数据。GraphQL 允许你在查询的任何位置请求 __typename,一个元字段,以获得那个位置的对象类型名称。_typename 字段解析为 String,它允许你在客户端区分不同的数据类型。
此时查询到的结果可能是:
{
"data": {
"search": [
{
"__typename": "Human",
"name": "Han Solo",
"height": 1.8
},
{
"__typename": "Human",
"name": "Leia Organa",
"height": 1.5
},
{
"__typename": "Starship",
"name": "TIE Advanced x1",
"length": 9.2
}
]
}
}
此外,在这种情况下,由于 Human 和 Droid 共享一个公共接口(Character),你可以在一个地方查询它们的公共字段,而不必在多个类型中重复相同的字段:
{
search(text: "an") {
__typename
... on Character {
name
}
... on Human {
height
}
... on Droid {
primaryFunction
}
... on Starship {
name
length
}
}
}
Apollo GraphQL
Apollo 是一个开源的 GraphQL 开发平台,提供了符合 GraphqQL 规范的服务端和客户端实现。使用 Apollo 可以帮助我们更方便快捷的开发使用 GraphQL。
- 官网:www.apollographql.com/
- GitHub 相关开源仓库:github.com/apollograph…
基本用法
参考: www.apollographql.com/docs/apollo…
mkdir graphql-server-example
cd graphql-server-example
npm init --yes
npm install apollo-server graphql
touch index.js
index.js:
const { ApolloServer, gql } = require('apollo-server');
// 定义 scheme
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const books = [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' },
];
// 定义 resolvers
// 与直接使用 graphql 不同之处在于 resolvers 里返回的结果要包在 Query 里
// 同理 Mutation 类型也要包裹在 Mutation 里
const resolvers = {
Query: {
books: () => books,
},
};
// 创建 ApolloServer 实例
const server = new ApolloServer({ typeDefs, resolvers });
// listen 方法开启一个 web server,默认端口 4000
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
与 Node.js 中间件集成
Apollo Server 可以轻松地与几个流行的 Node.js 中间件集成。例如 express, koa。下面以express 为例。
参考:www.apollographql.com/docs/apollo…
npm install apollo-server-express apollo-server-core express graphql
const { ApolloServer, gql } = require('apollo-server-express');
const { ApolloServerPluginDrainHttpServer } = require('apollo-server-core');
const express = require('express');
const http = require('http');
async function startApolloServer(typeDefs, resolvers) {
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
server.applyMiddleware({ app });
await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}
// 定义 scheme
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const books = [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' },
];
// 定义 resolvers
const resolvers = {
Query: {
books: () => books,
},
};
startApolloServer(typeDefs, resolvers)
Resolvers - 参数处理
对于有入参的情况,与直接使用 Graphql 不同,参数位于第二个位置
type User {
id: ID!
name: String
}
type Query {
user(id: ID!): User
}
const resolvers = {
Query: {
user(parent, args, context, info) {
return users.find(user => user.id === args.id);
}
}
}
Resolvers - 解析链
const libraries = [{ branch: 'downtown' }, { branch: 'riverside' }];
const books = [
{ title: 'The Awakening', author: 'Kate Chopin', branch: 'riverside' },
{ title: 'City of Glass', author: 'Paul Auster', branch: 'downtown' },
];
const typeDefs = gql`
type Library {
branch: String!
books: [Book!]
}
type Book {
title: String!
author: Author!
}
type Author {
name: String!
}
type Query {
libraries: [Library]
}
`;
假设有以上的 scheme 以及 data, 如果想要查询:
query GetBooksByLibrary {
libraries {
books {
title
author {
name
}
}
}
}
必须通过以下方法:
libraries 中返回的每一个对象都作为 Parent 传入 Library.books 的第一个参数,通过与 parent.branch 对比得到了对应的 books。books 下的 title 可以直接返回,但是 author 要以对象的形式返回,所以,books 返回的对象作为 Parent 传入 Book.author 的第一个参数,以此返回 author 的正确格式。
const resolvers = {
Query: {
libraries() {
return libraries;
}
},
Library: {
books(parent) {
return books.filter(book => book.branch === parent.branch);
}
},
Book: {
author(parent) {
return {
name: parent.author
};
}
}
};
Resolvers - context
// Constructor
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
authScope: getScope(req.headers.authorization)
})
}));
// Example resolver
(parent, args, context, info) => {
if(context.authScope !== ADMIN) throw new AuthenticationError('not admin');
// Proceed
}