一、GraphQL是什么
- 根据官网的解释是一种用于API的查询语言
- 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,减少数据的冗余。
- 简单来说,后端不需要考虑前端获取哪些数据,只需要把可以返回的全部返回,而前端可以精确的获得想要的数据。比如后端使用GraphQL查询出某个库A,B,C,D等若干字段,可以全部返回,前端就可以随意的获取想要的字段,比如只想要A,C。不需要和后端交流直接获得。
二、graphql基本使用
- 安装graphql,这里用的是v15.4.0
yarn add graphql@15.4.0
复制代码
- 创建index.js文件,开始使用
- 导入graphql
const { graphql, buildSchema } = require('graphql')
复制代码
- 使用GraphQL schema语法构建一个schema,表示服务端可以查询的信息
- buildSchema中的字符串解释:type Query 定义的是查询入口,count代表可以查询到count字段,count后的Int,表示count的类型
const schema = buildSchema(`
type Query {
count:Int
}
`)
复制代码
- 定义schema的resolver
- 这里就是接口逻辑部分
const rootValue = {
count(){
return 123
}
}
复制代码
- 连接schema和resolver,并查询
graphql(schema,'{count}',rootValue).then(res=>{
console.log(res)
})
复制代码
三、graphql结合express使用
- 安装express、express-graphql@0.12.0、graphql@15.4.0
const {buildSchema} = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const app = express()
复制代码
- 使用GraphQL schema语法构建schema
const schema = buildSchema(`
type Query {
count:Int
}
`)
复制代码
- 定义schema的resolver
const rootValue = {
count(){
return 123
}
}
复制代码
- 将graphql挂载到express中间件
app.use('/graphql',graphqlHTTP({
schema,
rootValue,
graphiql:true //开启浏览器graphql ide调试工具
}))
复制代码
- 启动web服务
app.listen(4000,()=>{
console.log('服务已运行在localhost:4000')
})
复制代码
- 在前端 使用axios请求graphql
axios({
method:'POST', //graphql的请求方法必须是POST
url:'http://localhost:4000/graphql',
data:{
query:'{count}'
}
}).then(res=>{
console.log(res)
})
复制代码
四、Graphql类型
- 在声明schema时 需要定义查询的入口 Query,并且在Query中定义可以被查询的字段及返回值类型
- Graphql内置类型 String Int Float Boolean ID。如果在类型后面添加! 表示该字段不能为null
- Query严格来说是一种对象类型
- Query是所有查询的入口点
- Query必须有 且不能重复
- Query中的可被查询的字段 每个类型都可以为空
- 对于对象类型,需要自定义一个类型 描述对象中的属性
- 对应数组类型 需要以 []形式 ,中括号中填写数组中每项的类型
- 枚举类型声明时 使用enum关键字 enum Test
type Score{
name:String
score:Float
}
enum Gender {
MALE
FEMALE
}
type User {
name:String
age:Int
hobbies:[String!]!
sores:[Score]
gender:Gender
}
type Query {
foo:String!
count:Int
salary:Float
isGood:Boolean
userId:ID
user:User
}
复制代码
五、修改字段
- 除了使用Query进行查询外 还可以使用Mutation进行修改
- 首先定义修改Schema
// 参数对象必须使用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
}
复制代码
- 在resolver中声明修改方法
createArticle({article}){
articles.push(article)
return articles
}
deleteArticle({id}){
const index = articles.find(article=>article.id === id)
articles.splice(index,1)
return {
success:true
}
}
复制代码
六、使用Apollo-Server
- 一般使用apollo-server比较多
- 安装Apollo-server 并引入
yarn add apollo-server
const { ApolloServer , gql } = require('apollo-server')
复制代码
- 定义schema
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'
}
]
复制代码
- 定义resolver
const resolvers = {
Query:{
books:()=>books
}
}
复制代码
- 创建ApolloServer实例 并运行
const server = new ApolloServer({typeDefs,resolvers})
server.listen().then(({url})=>{
console.log(url)
})
复制代码
七、apollo-server结合express
- 安装express apollo-server-express 并导入
const express = require('express')
const {ApolloServer , gql} = require('apollo-server-express')
复制代码
- 创建中间件
const app = express()
const server = new ApolloServer({typeDefs,resolvers})
server.applyMiddleware({app})
app.use((req,res)=>{
res.status(200)
res.send('Hello')
res.end()
})
app.listen({ port: 4000 }, () =>
console.log(`? Server ready at http://localhost:4000${server.graphqlPath}`)
)
复制代码
- 在resolver中处理查询,查询方法会接收很多参数,客户端的查询参数在args中
const resolvers = {
Query: {
// args: 客户端的查询参数
user(parent, args, context, info) {
console.log(args)
return users.find(user => user.id === args.id);
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END