不懂的地方仍是有不少,分享一下学习的心得,若是有错误,还望各位大佬斧正~javascript
GraphQL,是Facebook开源的一种api查询语言,对查询数据提供了一套完整的描述,客户端能够精准的获取须要的数据,而没有任何冗余css
最基础的查询方式如上图,左边是请求,右边是响应,我但愿获取todoList
这个集合,集合里的每个元素都包括_id,content,completed
字段,服务端返回的数据就是我请求须要的数据,不会多也不会少html
type todo {
_id: ID!
content: String!
completed: Boolean!
}
复制代码
todo
表示这是一个GraphQL的对象_id
、content
和completed
是todo
中的字段,ID
、String
、Boolean
都是graphql内置的类型String!
表示这个字段的值为String
类型且不可为空接着建立一个查询vue
type Query {
todoList: [todo]!
}
复制代码
Query
和Mutetion
都是GraphQL的关键字,一个表明查询,一个表明变动,在这里使用了Query
建立了一个查询[todo]!
表示字段todoList
的值是一个上面定义的todo
类型的数组,[todo]!
表示这个字段要么是空数组[]
,要么是元素为todo
的数组[todo,todo,...]
Int
: 有符号的32位整数Float
: 有符号的双精度浮点值String
: UTF‐8的字符串Boolean
: 布尔ID
: 惟一的标识,在序列化为String
时表示人类不可读的还能够自定义类型html5
了解了查询,就来建立一个GraphQL的服务器吧 我使用的是Apollo GraphQL,这是一个很是完整的GraphQL的实现,包括了客户端和服务端 node服务器使用的是koa 如今就开始吧java
首先建立一个项目,而后安装如下依赖node
npm i -S apollo-server-koa graphql koa
react
根目录建立app.js
文件ios
const Koa = require("koa");
const { ApolloServer } = require("apollo-server-koa");
const { gql } = require("apollo-server-koa");
// 定义从服务器获取数据的graphql方法
const typeDefs = gql` type todo { _id: ID! content: String! completed: Boolean! } type Query { todoList: [todo]! } `;
const server = new ApolloServer({
// 使用gql标签和字符串定义的graphql的DocumentNode
typeDefs,
// 开启mock
mocks: true
});
const app = new Koa();
// applyMiddleware将graphql服务链接到koa框架
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
复制代码
接着运行node app.js
,在http://localhost:4000/graphql
就能看见apollo server
提供的playground
了git
查询
{
todoList{
_id
content
completed
}
}
复制代码
在左边输入上方的查询,右边就会出现mock的数据了
resolvers是用于解析typeDefs查询的解析器,是一个键为type
名,值为一个函数的映射 在app.js
中添加resolvers
// ...
// 建立一个数据
const data = [
{
_id: "5ca16ed7c39e5a03d8ad3547",
content: "html5",
completed: false
},
{
_id: "5ca16ee0c39e5a03d8ad3548",
content: "javascript",
completed: false
},
{
_id: "5ca16ee5c39e5a03d8ad3549",
content: "css",
completed: false
}
];
// resolvers
// Query对应查询,todoList是一个函数,返回的是数据
// 能够写异步函数,用于真实的数据库查询
const resolvers = {
Query: {
todoList: () => data
}
};
// 添加resolvers,取消掉mocks
const server = new ApolloServer({
typeDefs,
resolvers,
});
const app = new Koa();
//...
复制代码
再次查询,返回的结果就是data
的数据了
Mutation能够对应REST API中的CRUD,一个简单的mutation
以下 在typeDefs
中增长
type updateResponse {
success: Boolean!
todoList:[todo]!
}
type Mutation {
addTodo(content: String): updateResponse!
}
复制代码
这是一个Mutation的操做,增长一个todo
项,返回一个updateResponse
对象
addTodo(content: String)
接收一个为String
类型的参数updateResponse
值包括一个键名为success
值为Boolean
和一个键名为todoList
值为todo
的数组修改resolvers
const resolvers = {
Query: {
todoList: () => data
},
Mutation: {
addTodo: (_, { content }) => {
console.log(content);
data.push({
_id:Math.random().toString(36).substring(3),
content,
completed:false
});
return { success: true, todoList:data };
},
}
};
复制代码
函数中具体的参数可查阅Resolver type signature
执行
mutation{
addTodo(content:"css"){
success
todoList{
_id
content
completed
}
}
}
复制代码
mutation
表示这是一个mutation
操做,操做名为addTodo
,接收一个名为content
类型为String
的参数,返回的数据是success
和todoList
在nodejs的控制台能看见console出来的参数
官方提供了包括react
、react-native
、vue
、augular
、native-ios
...等 在creact-react-app中使用
虽然官方提供了组件模式的Query
和Mutation
组件,不过我在学习过程当中,用的仍是直接以JS写的方法模式,Client api参考
在create-react-app
的项目中安装依赖
npm install apollo-boost react-apollo graphql --save
建立client.js
,并在package.json
中增长proxy
import ApolloClient from "apollo-boost";
const Client = new ApolloClient();
const getList = async () => {
return await Client.query({
query: gql` { todoList { _id content completed } } `
});
};
const add = async content => {
return await Client.mutate({
// 参数,content对应的下面的$content
variables: { content },
mutation: gql` mutation add($content: String!) { addTodo(content: $content) { success todoList{ _id content completed } } } `
})
};
export {getList,add};
复制代码
我使用的是webstorm是一款集成功能很是强大的IDE,在plugins里搜索安装JS GraphQL
导出schema.json
npm install -g apollo-codegen
apollo-codegen introspect-schema http://localhost:4000/graphql --output graphql.schema.json
webstrome就会提供很是智能的graphql代码格式化和补全功能了
学习过程当中写了2个demo,数据库使用的mongodb,之前也没用过,也是现学的,好多都不懂……
不懂的地方依旧不少,文档是英文的又特别复杂,路漫漫其修远兮~
公司确定不会用graphql的,rest api都成问题,唉……